Nick Ginanto
Nick Ginanto

Reputation: 32130

node.js know the file of where the require happened

I have 2 files

// file1.js
//some js code that will do what I ask in the question
module.exports = myFunc

//file2.js
require('./file1')

Is it possible, in any kind of way, for file1.js to know who required it? so when file2 requires file1, file1 will know that it was file2?

Upvotes: 0

Views: 60

Answers (1)

Matt Way
Matt Way

Reputation: 33161

You noted that you wanted to use file1s functionality to create a file that is the same name as the callers. You could do this by utilising the __filename variable within a module.

Rather than try and access the caller, just pass this variable when using file1. For example:

require('./file1')(__filename)

Where file1 has something like:

module.exports = filename => {
    // create file here
}

While this should solve your problem, it seems like a strange requirement, and there is likely a better way to achieve what you are really after.

Upvotes: 2

Related Questions