Let's say I have this directory structure
Project/config/file.json
Project/foo.js
Project/node_modules/SomeModule/bar.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
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
asume process.cwd() == '/home/usr/node/'
if route == './directory' it would become '/home/usr/node/directory'
if route == '/home/usr/node/directory' it will be left as is
I hope it works for you :D