我正在使用以下内容从parent.js
文件中打印文件名:
let path = require('path');
let fileName = path.basename(__filename);
console.log(fileName);
但是,我正在从parent.js
文件中调用child.js
文件,我实际上想从child.js
文件中打印parent.js
的文件名,例如
console.log(childFileName + " is being called by " + parentFileName);
childFileName is being called by parentFileName
您可以执行以下操作:
父.js
const path = require('path');
const fileName = path.basename(__filename);
const child = require('child.js')(fileName)
孩子.js
const path = require('path');
const fileName = path.basename(__filename);
module.exports = (requiredFrom = 'Somewhere') => {
console.log(`${fileName} is being called from ${requiredFrom}`);
}
此方法需要以调用方名称作为参数的子文件,这将使它从所需文件中用作参数,如果返回函数,则可以使用该参数module.exports
编辑 1
我宁愿只需要子文件中的路径并从那里打印或使用其他工具
关键部分是将必要的信息从父级传递给子级,这在这里发生:
const child = require('child.js')(fileName)
因此,要在不需要对父文件.jspath
的情况下执行相同的操作,您可以执行以下操作:
父.js
const child = require('child.js')(__filename);
孩子.js
const path = require('path');
const fileName = path.basename(__filename);
module.exports = (fileFrom = '') => {
const requiredFrom = path.basename(fileFrom) || 'Somewhere';
console.log(`${fileName} is being called from ${requiredFrom}`);
}
无论如何,一旦您需要在应用上的任何位置使用path
模块,它就会被缓存,因此这不会提高应用的性能。
另外,其他方面
您也可以以糟糕或黑客的方式执行此操作,它可能适合您的需求:
父.js
const child = require('child.js');
孩子.js
const path = require('path')
const fileName = path.basename(__filename);
const requiredFrom = module.parent.filename;
console.log(`${fileName} is being called from ${requiredFrom}`);
delete require.cache[__filename]
此 aproach 的缺点是您将失去保留子文件不同要求的值的能力.js(每次需要时,这会从require.cache
中删除该文件(