Cannot find file in Node even though it has correct path

srpalo picture srpalo · Jan 11, 2017 · Viewed 13.5k times · Source

After executing this code:

const filename = "../../.dburl"
const url = fs.readFileSync(filename, 'utf-8')

I recieve the following error:

Error: ENOENT: no such file or directory, open '../../.dburl'

What I know so far:

1) The filepath is correct.

2) My application has permission to read the file.

3) .dburl is not read even when stored in the same directory as the application.

Any help is much appreciated ... Thanks!

Answer

bsyk picture bsyk · Jan 12, 2017

You can use the module-level variable '__dirname' to get the directory that contains the current script. Then you can use path.resolve to use relative paths.

console.log('Path of file in parent dir:', require('path').resolve(__dirname, '../app.js'));