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: https://stackoverflow.com/questions/7899403/how-to-get-details-of-npm-installed-modules-programatically
NPM's primary job is "to put things on your computer." 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 command 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)
}