最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to programmatically get the location where npm installs global modules - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 4

NPM'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')
发布评论

评论列表(0)

  1. 暂无评论