Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS readdir and require relative paths

Tags:

node.js

module

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

like image 298
eSinxoll Avatar asked Nov 21 '12 07:11

eSinxoll


1 Answers

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

like image 73
Marco Gabriel Godoy Lema Avatar answered Oct 03 '22 23:10

Marco Gabriel Godoy Lema