node.js 知道发生需求的文件
node.js know the file of where the require happened
我有 2 个文件
// file1.js
//some js code that will do what I ask in the question
module.exports = myFunc
//file2.js
require('./file1')
是否有可能以任何方式让 file1.js 知道谁需要它?所以当 file2 需要 file1 时,file1 会知道它是 file2 吗?
您注意到您想要使用 file1
的功能来创建一个与调用方同名的文件。您可以通过在模块中使用 __filename
变量来做到这一点。
与其尝试访问调用者,不如在使用 file1
时传递此变量。例如:
require('./file1')(__filename)
其中 file1
类似:
module.exports = filename => {
// create file here
}
虽然这应该可以解决您的问题,但这似乎是一个奇怪的要求,并且可能有更好的方法来实现您真正想要的。
我有 2 个文件
// file1.js
//some js code that will do what I ask in the question
module.exports = myFunc
//file2.js
require('./file1')
是否有可能以任何方式让 file1.js 知道谁需要它?所以当 file2 需要 file1 时,file1 会知道它是 file2 吗?
您注意到您想要使用 file1
的功能来创建一个与调用方同名的文件。您可以通过在模块中使用 __filename
变量来做到这一点。
与其尝试访问调用者,不如在使用 file1
时传递此变量。例如:
require('./file1')(__filename)
其中 file1
类似:
module.exports = filename => {
// create file here
}
虽然这应该可以解决您的问题,但这似乎是一个奇怪的要求,并且可能有更好的方法来实现您真正想要的。