Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting directory from which node.js was executed

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?

like image 731
ciembor Avatar asked Mar 01 '13 02:03

ciembor


People also ask

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 get the current working directory in typescript?

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.

What is cwd in NodeJS?

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.

How do I list directories in node JS?

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 .


2 Answers

process.cwd() will provide that.

like image 52
JohnnyHK Avatar answered Oct 14 '22 22:10

JohnnyHK


__dirname gives you the path where a file resides.

like image 45
Pascal Belloncle Avatar answered Oct 14 '22 23:10

Pascal Belloncle