Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically get the location where npm installs global modules

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?

like image 345
B T Avatar asked Jun 21 '13 07:06

B T


People also ask

Where are global npm modules installed?

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.

Where are npm modules located?

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.

How do I see which NPM packages are installed globally?

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.

Where does npm install download packages from?

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.


2 Answers

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'));
})
like image 111
Doug Amos Avatar answered Oct 06 '22 00:10

Doug Amos


If you don't want to depend on npm:

const { resolve } = require('path')    
const globalPath = resolve(process.execPath, '../../lib/node_modules')
like image 34
justmoon Avatar answered Oct 06 '22 00:10

justmoon