Warns if the process has been started with the wrong cwd
rwd means real working directory.
Global modules don't need the
Did you know why the people prefix
__dirname before a path?
var fs = ;fs;
It's because the
process.cwd() function returns the shell's current working directory instead of the directory where lives the main script of your application.
Look at this example:
$ pwd /home/user1 $ mkdir dir $ cat > dir/app.js console.log (process.cwd ()); $ node dir/app.js /home/user1 $ cd dir && node app.js /home/user1/dir
If you execute the main script with a relative path like the above example (
$ node dir/app.js), very bad things could happen and it's nearly impossible to detect why your code is not working as expected. This is a feature found on all the programming languages because it's a thing related with the OS, not with the programming language itself.
$ node dir/app behaves different than
$ cd dir && node app.
The following example illustrates a very ingenuous script, but depending on how you execute it, very dangerous things could happen:
//$ node dir/app.jsvar fs = ;if fs;else//Warning!!;
This can be easily fixed changing the cwd at runtime, but it's discouraged. The best way to ensure that the application is started correctly is to require the
rwd module. I recommend to put it in the very first line of your main file:
The module is automatically uncached.
Then, if you start the process with a relative path, eg:
$ node dir/app.js, a message will be printed and the process will exit with code 1, something similar to this:
The process has been started this way: $ node dir/app.js Better alternatives: $ cd dir && node app.js $ node <absolute_path>/dir/app.js
This way, you don't need to prefix the paths with
__dirname because if the process doesn't finish this means that the cwd is the same as the directory of the main file.
For your convenience you can create a global variable similar to
__dirname which can be used safely from any module (
__dirname is local to the file). For example, you can run this snippet in the main file:
var path = ;global__root = path;
Then, every time you need to use a relative path from the root, you can prefix it with
var fs = ;if fs;