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?
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?
Share Improve this question edited May 23, 2017 at 12:05 CommunityBot 11 silver badge asked Jun 21, 2013 at 7:19 B TB T 61k36 gold badges198 silver badges209 bronze badges3 Answers
Reset to default 4NPM's primary job is "to put things on your puter." Their folders documentation details what it puts where
Due to differences between operating systems, the .npmrc
config, and the prefix
property, it's easiest to rely on npm to determine the global install directory by using npm root
like this:
$ npm root -g
You can execute a mand line binary with Node.js like this:
const { exec } = require('child_process')
const { promisify } = require('util');
async function main() {
let execAsync = promisify(exec);
let { stdout: globalPath } = await execAsync("npm root -g");
console.log(globalPath);
}
Alternatively, in order to access the npm module programmatically, you'll need to install it locally:
$ npm i npm --save
And then you can run the following code:
const npm = require("npm")
const { promisify } = require('util');
async function main() {
await promisify(npm.load)()
let globalPath = npm.root
console.log(globalPath)
}
Further Reading
- Where does npm install packages?
- Global npm install location on windows?
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')