Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 300
Zhang Avatar asked Nov 18 '12 04:11

Zhang


People also ask

How do I change the path in node JS?

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.

How do I run a node js file locally?

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.

How do I find the path of a node js file?

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.

How do I copy files from one directory to another in node JS?

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.


2 Answers

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.

like image 178
Julian Lannigan Avatar answered Sep 27 '22 21:09

Julian Lannigan


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.

like image 27
chbrown Avatar answered Sep 27 '22 20:09

chbrown