Executing Node.js file from outside the folder breaks file path

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?

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.

Or

var path = require('path');
var key = path.join(__dirname, 'cert_and_key_dev.pem');
var certPem = fs.readFileSync(key, encoding='ascii');

If you don't want to cd for whatever reason.