NodeJS readdir and require relative paths

14,211

As Dan D. expressed, fs.readdir uses process.cwd() as start point, while require() uses __dirname. If you want, you can always resolve from one path to another, getting an absolute path both would interpret the same way, like so:

var path = require('path');
route = path.resolve(process.cwd(), route);

That way, if using __dirname as start point it will ignore process.cwd(), else it will use it to generate the full path.

For example, assume process.cwd() is /home/usr/node/:

  • if route is ./directory, it will become /home/usr/node/directory
  • if route is /home/usr/node/directory, it will be left as is

I hope it works for you :D

Share:
14,211
eSinxoll
Author by

eSinxoll

Updated on June 27, 2022

Comments

  • eSinxoll
    eSinxoll almost 2 years

    Let's say I have this directory structure

    /Project
       /node_modules
          /SomeModule
             bar.js
       /config
          /file.json
       foo.js
    

    -

    foo.js:
    require('bar');
    

    -

    bar.js:
    fs.readdir('./config'); // returns ['file.json']
    var file = require('../../../config/file.json');
    

    Is it right that the readdir works from the file is being included (foo.js) and require works from the file it's been called (bar.js)?

    Or am I missing something? Thank you