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?
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.
cwd() method in Node.
__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()
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.
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
)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)
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