Executing Node.js file from outside the folder breaks file path
Problem
I have a Node.js file called "server.js".
In the script, I am opening some files using something like:
var certPem = fs.readFileSync('cert_and_key_dev.pem', encoding='ascii');
Using the Bash Shell, if I cd into the directory where the server.js is, and run the command:
[mybashshell]$ node server.js
It works, I got no error. Server launches and runs.
Now when I cd OUT OF the directory where the server.js file is, then run the same Shell Command again to launch my server.
It complains about my file Path to my "cert_and_key_dev.pem" being broken.
I wasn't expecting something like this to happen. I though the path used in the script file being executed should be relative to the script file, not to the location where I executed my bash shell command.
Any ideas?
Solution
Put this at the beginning of your script.
process.chdir(__dirname);
This will change the process's working directory into the directory path of the file (__dirname
) being executed.
For more information on the function read this.
Discussion
View additional discussion.