Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the dirname of the calling method when it is in a different file in nodejs?

Tags:

node.js

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?"

like image 288
deitch Avatar asked Aug 09 '13 10:08

deitch


People also ask

What does __ Dirname mean in Node?

__dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file.

How do I use dirname in node JS?

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.

How can I get the directory name of the current module using variables?

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.

Why __ Dirname is not defined?

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!


1 Answers

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));   } }; 
like image 155
Laurent Perrin Avatar answered Sep 21 '22 00:09

Laurent Perrin