node.js require Library Path Get

Getting the Path of a Library Referenced by require in Node.js

For example, which node package does the node program in the current directory reference? It should be the node_modules in the current directory, but in some cases it references the default node_modules specified in the node path. In such cases, even if you post the current directory's repository to GitHub, the execution environment cloned in any environment will result in a package not found error.

Shou Arisaka
2 min read
Nov 18, 2025

For example, which node package does the node program in the current directory reference? It should be the node_modules in the current directory, but in some cases it references the default node_modules specified in the node path. In such cases, even if you post the current directory’s repository to GitHub, the execution environment cloned in any environment will result in a package not found error.

e.g. Example where the current directory is /mnt/c/pg/, packages.json is not defined, but the default node_path /mnt/c/pg/node/ is used

/mnt/c/pg$ node
> require.resolve('express')
'/mnt/c/pg/node/node_modules/express/index.js'

e.g. Example where express and moment can reference the node_modules in the current directory, but cors is not found so the default is referenced

/mnt/c/pg/web/vue_dev$ node
> require.resolve('cors')
'/mnt/c/pg/node/node_modules/cors/lib/index.js'
> require.resolve('express')
'/mnt/c/pg/web/vue_dev/node_modules/express/index.js'
> require.resolve('moment')
'/mnt/c/pg/web/vue_dev/node_modules/moment/moment.js'

Furthermore, even if a package is installed locally in the current directory, it could cause problems later depending on whether it’s installed as a dependency and being used, or whether it’s properly installed with a version specified in packages.json.

For example, if express is not defined in packages.json but ./node_modules/express/index.js can be referenced locally, it means that an arbitrary version of express installed as a dependency of some other package is being used.

npm list -g | less
npm list | less

It’s important to use npm list and other tools to confirm where in the dependency tree it’s located, what version it is, and whether all packages used at the top level are specified in packages.json.

(Reference)

In node.JS how can I get the path of a module I have loaded via require that is not mine (i.e. in some node_module) - Stack Overflow

Share this article

Shou Arisaka Nov 18, 2025

🔗 Copy Links