Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the path to the current script with Node.js?

Tags:

node.js

How would I get the path to the script in Node.js?

I know there's process.cwd, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in /home/kyle/ and I run the following command:

node /home/kyle/some/dir/file.js 

If I call process.cwd(), I get /home/kyle/, not /home/kyle/some/dir/. Is there a way to get that directory?

like image 379
Kyle Slattery Avatar asked Jun 28 '10 14:06

Kyle Slattery


People also ask

How do I specify a path in NodeJs?

The best way to work with paths - use path module (API): Or with path module: var path = require('path'); path. join('E:','Thevan','Some File.

Which command is used to print the current working directory in NodeJs?

cwd() method in Node.

What is __ Dirname in NodeJs?

__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file. Difference between process.cwd() vs __dirname in Node.js is as follows: process.cwd()

How do I run a node script from the command line?

You can Run your JavaScript File from your Terminal only if you have installed NodeJs runtime. If you have Installed it then Simply open the terminal and type “node FileName. js”. If you don't have NodeJs runtime environment then go to NodeJs Runtime Environment Download and Download it.


2 Answers

I found it after looking through the documentation again. What I was looking for were the __filename and __dirname module-level variables.

  • __filename is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js)
  • __dirname is the directory name of the current module. (ex:/home/kyle/some/dir)
like image 129
Kyle Slattery Avatar answered Oct 25 '22 09:10

Kyle Slattery


So basically you can do this:

fs.readFile(path.resolve(__dirname, 'settings.json'), 'UTF-8', callback); 

Use resolve() instead of concatenating with '/' or '\' else you will run into cross-platform issues.

Note: __dirname is the local path of the module or included script. If you are writing a plugin which needs to know the path of the main script it is:

require.main.filename 

or, to just get the folder name:

require('path').dirname(require.main.filename) 
like image 30
Marc Avatar answered Oct 25 '22 11:10

Marc