Handling relative paths across modules in javascript

Viewed 713

So let's say I have a .js file which exposes a function, which I want to be able to import in many other files. The function in this file needs access to some data stored in a certain file ( take .txt for this example) and I'm using the relative address to read and write to this text file.

Now the problem comes when I import this module into other files in different directories, the relative paths won't be valid but I don't know how I can change this? I'm sure there's a simple way to do this but I can't figure it out at all.

file 1

relative path = '../../file.txt'
function foo(){
  fs.readFile(relativePath)
}
module.exports = {foo}

file 2

const {foo} = require('foo')
foo();
2 Answers

It doesn't actually matter which other modules load this module. The path is going to be resolved relative to the current working directory, which depends on in which directory your shell is in when you invoke the code.

If you want it to resolve relative to that specific JavaScript file, then you can use __dirname:

const path = require('path');
// ...
fs.readFile(path.join(__dirname, relativePath));

you can use resolve method of path package like

const path = require('path').resolve
path.resolve('../../file.txt')
Related