2

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();
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    I assume we're talking about node context? If so, I think we have a duplicate here: https://stackoverflow.com/questions/38829118/nodejs-convert-relative-path-to-absolute – Constantin Groß May 11 '21 at 15:40
  • I think my goal is slightly different so this isn't a duplicate. path.resolve() isn't doing the trick for me but I did find the second answer using __dirname to be useful and I can write a small helper function using that to accomplish my goal I think. so thanks. – ARandomDeveloper May 12 '21 at 12:08

2 Answers2

3

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));
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
-1

you can use resolve method of path package like

const path = require('path').resolve
path.resolve('../../file.txt')
Waleed Ahmad
  • 446
  • 3
  • 15
  • Could you elaborate on where I can call this? When I call this it resolves the path from the current working directory but I want the path from the module file which I will be importing or I can't read the txt file. Thanks – ARandomDeveloper May 12 '21 at 12:03