Let's say I have two files, dir/a.js
and lib/b.js
a.js:
b = require('../lib/b'); b.someFn();
b.js:
var fallback = "./config.json"; module.exports = { someFn = function(jsonFile) { console.log(require(jsonFile || fallback); } }
The entire purpose of b.js
in this example is to read a json file, so I might call it as b.someFn("path/to/file.json")
.
But I want there to be a default, like a config file. But the default should be relative to a.js and not b.js. In other words, I should be able to call b.someFn()
from a.js
, and it should say, "since you didn't pass me the path, I will assume a default path of config.json
." But the default should be relative to a.js
, i.e. should be dir/config.json
and not lib/config.json
, which I would get if I did require(jsonFile)
.
I could get the cwd
, but that will only work if I launch the script from within dir/
.
Is there any way for b.js
to say, inside someFn()
, "give me the __dirname
of the function that called me?"
__dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file.
The __dirname in a node script returns the path of the folder where the current JavaScript file resides. __filename and __dirname are used to get the filename and directory name of the currently executing file. The ./ gives the current working directory. It works similar to process.
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.
The __dirname or __filename global variables are not available in ECMAScript module files. To solve the "__dirname is not defined in ES module scope" error, import and use the dirname() method from the path module. The dirname method takes a path as a parameter and returns the directory name of the path. Copied!
Use callsite, then:
b.js:
var path = require('path'), callsite = require('callsite'); module.exports = { someFn: function () { var stack = callsite(), requester = stack[1].getFileName(); console.log(path.dirname(requester)); } };
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