有没有办法获取Node.js中已加载模块的文件路径?

时间:2020-05-27 12:37:23

标签: node.js

给定已加载的模块,是否有可能获取其文件路径?

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,但是我需要相反的查找... 有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

require.main的文档描述了module对象。

该模块具有一个id和一个path,但是不会导出。您可以将这些属性添加到module.exports对象中以导出它们。然后,在单独的模块中,您可以通过MyOtherModule.idMyOtherModule.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.childrenmodule.parent,并且在访问时还必须使用module.exports,因此您可能只想包含idpath,如下:

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')

这可能会变得混乱。如果要导入不是作者的模块,则无法选择查找idpath(除非作者将其添加到module.exports中)。