I want to programmatically find out the folder where npm installs global modules. This question is similar, but the answer doesn't work for globally installed modules: How to get details of npm installed modules programatically?
Global modules are installed in the /usr/local/lib/node_modules project directory in the standard system, which is the system's root. Print the location of all global modules on your system using this command.
Global libraries On Unix systems they are normally placed in /usr/local/lib/node or /usr/local/lib/node_modules when installed globally. If you set the NODE_PATH environment variable to this path, the modules can be found by node.
To view the npm global packages list and their dependencies, you can run the following npm list command followed by the “-g” flag where g stands for global. As you can see in the above result, all the global packages are displayed in a tree-like structure.
If it finds that package (which it does), npm installs it to the project in an automatically generated node_modules folder (more on this in a bit) located in the project root folder, including everything the package needs to run.
From the nodejs website:
globally - This drops modules in {prefix}/lib/node_modules, and puts executable files in {prefix}/bin, where {prefix} is usually something like /usr/local. It also installs man pages in {prefix}/share/man, if they’re supplied.
To get the prefix enter:
npm config get prefix
Edit:
To do it from node use the npm npm module. Something like this will work:
var npm = require("npm")
var myConfigObject = {}
npm.load(myConfigObject, function (er) {
if (er) return handleError(er)
console.log(npm.get('prefix'));
})
If you don't want to depend on npm:
const { resolve } = require('path')
const globalPath = resolve(process.execPath, '../../lib/node_modules')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With