Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current path of the file that run the script in nodejs

Tags:

So I have node modules that can be require for Internationalization.

I'm trying to get the current path of the file that run my node module inside the nodule module.

Use case #1:

Inside ~/yourProject/node_modules/i18n.js

var current_path_to_locales_dir = path.join(__dirname, "locale");

And the path of the server is:

~/YourUserName/yourProject/app.js

Doing var i18n = require("i18n");

And trying to get the path it will return

/User/YourUserName/yourProject/node_modules/locale

Which is correct but I'm expecting it to look for

/User/YourUserName/yourProject/locale

Use case #2:

Inside ~/i18nProject/i18n.js

var current_path_to_locales_dir = path.join(__dirname, "locale");

If I have a sample app in the ~/i18nProject/sample and doing var i18n = require("../i18n");

The locale directory this time will be

/User/YourUserName/i18nProject/locale

Again the above is correct but I would expect it to be

/User/i18nProject/sample/locale/

Now I'm wondering if there is a way that I can get the path of the current running script?

like image 789
Ali Avatar asked Dec 17 '13 18:12

Ali


People also ask

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

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 find the path of a file in node?

To check the path in synchronous mode in fs module, we can use statSync() method. The fs. statSync(path) method returns the instance of fs. Stats which is assigned to variable stats.

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

cwd() method in Node.


1 Answers

Use the variables __filename, __dirname will return called modules/scripts name and path, see here http://nodejs.org/docs/latest/api/globals.html#globals_filename

Update

In your case you need to get the caller of module/script:

Node.js does not do it for you, so technically you may have to add extra wrapper and parameter to your module and convert it into a function that accepts this information.

However, there is a work around to implement getCaller by using Error.prepareStackTrace This thread already has your solution:

How can one get the file path of the caller function in node.js?

like image 86
Nitin... Avatar answered Oct 14 '22 14:10

Nitin...