aug
aug

Reputation: 11714

Node.js: How to get filename where function was required from within a module?

I'm trying to get the original filename from where a module's function has been required from. I know you can use __filename to get the current file, but I want to get the original file.

For example a simple module I have would be

module.js

module.exports(function() {
   return {
     print : function(message) {
        console.log(__filename + ' ' + message);
     };
   }
});

app.js

var module = require('./module')();
module.print('hello');

What ends up happening is it will print module.js hello but I really want to see app.js hello.

I was exploring ways to get it and I know you can use console.trace to see the stack of calls but I can't parse it to do what I want.

Right now I've worked about it by making the print function take in another parameter and you simply pass __filename from within app.js but I kind of want to find a solution where I don't have to do this.

Upvotes: 5

Views: 4178

Answers (2)

Swivel
Swivel

Reputation: 3297

Getting Parent Module

You can do this by using module.parent , then resolving the filename property like so:

module.js

module.exports(function() {
   return {
     print : function(message) {
        console.log(module.parent.filename + ' ' + message);
     };
   }
});

app.js

var module = require('./module')();
module.print('hello');

Output:

/path/to/app.js hello

Which is almost what you're asking for.

Qualifying The Solution

This solution provides you with a fully qualified path, but you get the filename by splitting the path by its delimiter.

var parentModFilename = module.parent.filename.split(/\\|\//).pop()

Which would then give you "/app.js" in parentModFilename.

Upvotes: 9

Peter Lyons
Peter Lyons

Reputation: 146054

You can use require.resolve(moduleName) to get the full path to the file. path.basename can strip the parent directories. So in your example:

var path = require("path");
var module = require('./module')();
process.stdout.write(path.basename(require.resolve('./module') + " ");
module.print('hello');

Upvotes: 2

Related Questions