0

I need to do some file operations with paths relative to the script that required the current one.

Say we have the following in ~/somewhere/file2.js

const y = require('~/file1.js');

And in ~/file1.js we have:

const x = require('./other/script.js'); //relative to ~/file1.js

And we invoke it like this:

cd ~/somedir
node ~/somewhere/file2.js

then within ~/other/script.js we can do this:

console.log(__dirname);         // -> ~/other
console.log(__filename);        // -> ~/other/script.js
console.log(process.cwd());     // -> ~/somedir
console.log(process.argv[0]);   // -> path/to/node
console.log(path.resolve('.')); // -> ~/somedir
console.log(process.argv[1]);   // -> ~/somewhere/file2.js

None of these are the path I need.

How, from ~other/script.js, can I determine the location of the script that required us - i.e ~/file1.js

To put it another way. ~/somewhere/file2.js requires ~/file1.js and ~/file1.js requires ~/other/script.js from within ~/other/script.js I need to do file operations relative to ~/somewhere/file1.js - how can I get it's location?

I actually only need the directory in which file1.js sits, so filename or directory will work for me.

1 Answer 1

1

You can use module.parent.filename inside of other/script.js, or you can pass the __dirname as a parameter to your module like require('other/script.js')(__dirname) (given your module exports a function)

Sign up to request clarification or add additional context in comments.

1 Comment

path.dirname(module.parent.filename) sounds like exactly what I need, thanks. Although a word of warning to others finding this - the path given will be that of the first module to include this one. In my scenario there is only one, but if you have multiple then this approach may not be suitable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.