I have some project, and I run it with node main.js
/ make test
etc. What I need is to get this directory from a script. Not only from main.js
, but also from any submodule. I tried with path
plugin and __directory
, but I get a path of the current file (for example submodule). I also tried require('path').dirname(require.main.filename)
, but when I run make test
I get mocha dirname instead of my project directory. What is the easiest way to solve this?
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.
Using __dirname in a Node script will return the path of the folder where the current JavaScript file resides. Using ./ will give you the current working directory.
cwd() returns the current working directory, i.e. the directory from which you invoked the node command. __dirname returns the directory name of the directory containing the JavaScript source code file.
You can use the f. readdir() method to list all files available in a directory in Node. js. This method asynchronously reads the contents of the given directory and returns an array of the file names excluding .
process.cwd()
will provide that.
__dirname
gives you the path where a file resides.
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