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
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/
:
route
is ./directory
, it will become /home/usr/node/directory
route
is /home/usr/node/directory
, it will be left as isI hope it works for you :D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With