给定已加载的模块,是否有可能获取其文件路径?
const MyModule = require('./MyModule');
const MyOtherModule = require('../otherfolder/MyOtherModule');
function print(){
console.log(thisIsThePathTo(MyModule)); <--- Should print the absolute path of the loaded module
console.log(thisIsThePathTo(MyOtherModule)); <--- Should print the absolute path of the loaded module
}
我看到了require.resolve,但是我需要相反的查找... 有什么想法吗?
谢谢!
答案 0 :(得分:1)
require.main
的文档描述了module
对象。
该模块具有一个id
和一个path
,但是不会导出。您可以将这些属性添加到module.exports
对象中以导出它们。然后,在单独的模块中,您可以通过MyOtherModule.id
或MyOtherModule.path
例如,
在MyOtherModule/index.js
中:
myOtherModuleFunction = function() {
console.log('This is module 2')
}
module.exports = {
// spread all properties in module.exports
...module,
// then add the exports
exports: myOtherModuleFunction
}
和MyModule/MyModule.js
中的
module.exports = {
...module,
exports: { someFunction: () => console.log('MyModule') }
}
和MyModule/index.js
中的
const MyModule = require('./MyModule');
const MyOtherModule = require('../../MyOtherModule/');
function thisIsThePathTo(module) {
return module.path
}
function print(){
console.log(thisIsThePathTo(MyModule))
console.log(thisIsThePathTo(MyOtherModule))
}
print()
运行node src/MyModule/index.js
输出:
/.../stackoverflow/62043302/src/MyModule/
/.../stackoverflow/62043302/src/MyOtherModule
如果您打印module.id
而不是module.path
,则会得到:
/.../stackoverflow/62043302/src/MyModule/index.js
/.../stackoverflow/62043302/src/MyOtherModule/index.js
但是,传播所有属性包括module.children
和module.parent
,并且在访问时还必须使用module.exports
,因此您可能只想包含id
或path
,如下:
myOtherModuleFunction = function() {
console.log('This is module 2')
}
const { id, path } = module
module.exports = {
id,
path,
myOtherModuleFunction,
}```
and require like so:
```js
const {id: otherModuleId, myOtherModuleFunction } = require('MyOtherModule')
这可能会变得混乱。如果要导入不是作者的模块,则无法选择查找id
或path
(除非作者将其添加到module.exports
中)。