Udi
Udi

Reputation: 1110

Is there a way to get the file path for a loaded module in Node.js?

Is it possible, given a loaded module, to get its file path?

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
}

I saw require.resolve but I need the opposite lookup... Any ideas?

Thanks!

Upvotes: 2

Views: 284

Answers (1)

sbolel
sbolel

Reputation: 3524

The documentation for require.main describes the module object.

The module has an id and a path, however those are not exported. You can add those properties to the module.exports object to export them. Then, in a separate module, you can access them via MyOtherModule.id or MyOtherModule.path

For example,

In 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 
}

and in MyModule/MyModule.js,

module.exports = {
    ...module,
    exports: { someFunction: () => console.log('MyModule') }
}

and in 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()

Running node src/MyModule/index.js outputs:

/.../stackoverflow/62043302/src/MyModule/
/.../stackoverflow/62043302/src/MyOtherModule

And if you print module.id instead of module.path, you'll get:

/.../stackoverflow/62043302/src/MyModule/index.js
/.../stackoverflow/62043302/src/MyOtherModule/index.js

However, spreading all properties includes module.children and module.parent, and you'll also have to use module.exports when accessing the so you probably only want to include id or path, like so:

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

This can get messy. If you're importing modules you did not author, you will not have the option to lookup the id or path (unless the authors added it to module.exports).

Upvotes: 1

Related Questions