0

Imagine a directory structure like this:

module
  index.js

project
  main.js
  file.yaml

Imagine further that inside the module/index.js file, there is this code:

const fs = require('fs');

exports.test = function() {
  // How should I *dynamically* reference the caller's app root directory?
  console.log(fs.readFileSync('file.yaml', 'utf8'));
}

Inside the project/main.js file, there is this code:

const x = require('./module');

x.test();

And inside the project/file.yaml file, there is this code:

foo: bar

I want x.test(); to output the contents of project/file.yaml, somehow dynamically referencing the caller's root directory.

MystPi
  • 116
  • 2
  • 12
  • `__dirname` is the tool at your disposal. You can also try harvesting the path out of a [stack trace](https://stackoverflow.com/questions/2923858/how-to-print-a-stack-trace-in-node-js). – Wyck Nov 30 '21 at 16:40

1 Answers1

0

Is this what you wanted? __dirname gives the root dir of this file. So, no matter where this function gets called it will have correct location of file.yaml.

const fs = require('fs');

exports.test = function(fileLocation) {
  // How should I *dynamically* reference the caller's app root directory?
  console.log(fs.readFileSync(fileLocation), 'utf8'));
}
// Calling location
test(path.join(__dirname, './file.yaml')
rakesh shrestha
  • 1,335
  • 19
  • 37
  • Not exactly. I need `file.yaml` to be able to change location and still work, as this will become a npm package. – MystPi Nov 30 '21 at 17:22
  • hmm i don't think you can do that. But in packages you can pass the location of your file as a argument to your test function and read it from there. I have updated my answer – rakesh shrestha Dec 01 '21 at 01:55