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?
chdir() method is used for changing the current directory of the Node. js process. It will throw an exception if any error occurs or the process fails, but will not return any response on success.
The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.
We can get the path of the present script in node. js by using __dirname and __filename module scope variables. __dirname: It returns the directory name of the current module in which the current script is located. __filename: It returns the file name of the current module.
copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, Node. js will overwrite the file if it already exists at the given destination. The optional mode parameter can be used to modify the behavior of the copy operation.
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.
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