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