Search code examples
node.jsfs

Cannot find file in Node even though it has correct path


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!


Solution

  • 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'));