// windows: running 'npm blah' in this folder will invoke WSH, not node.
if (typeof WScript !== 'undefined') {
'npm does not work when run\n' +
'with the Windows Scripting Host\n\n' +
'"cd" to a different directory,\n' +
'or type "npm.cmd <args>",\n' +
'or type "node npm <args>".'
var unsupported = require('../lib/utils/unsupported.js')
unsupported.checkForBrokenNode()
var gfs = require('graceful-fs')
// Patch the global fs module here at the app level
var fs = gfs.gracefulify(require('fs'))
var EventEmitter = require('events').EventEmitter
var npm = module.exports = new EventEmitter()
var npmconf = require('./config/core.js')
var log = require('npmlog')
var inspect = require('util').inspect
// capture global logging
process.on('log', function (level) {
return log[level].apply(log, [].slice.call(arguments, 1))
log.verbose('attempt to log ' + inspect(arguments) + ' crashed: ' + ex.message)
var path = require('path')
var abbrev = require('abbrev')
var which = require('which')
var glob = require('glob')
var rimraf = require('rimraf')
var parseJSON = require('./utils/parse-json.js')
var aliases = require('./config/cmd-list').aliases
var cmdList = require('./config/cmd-list').cmdList
var plumbing = require('./config/cmd-list').plumbing
var output = require('./utils/output.js')
var startMetrics = require('./utils/metrics.js').start
var perf = require('./utils/perf.js')
perf.on('timing', function (name, finished) {
log.timing(name, 'Completed in', finished + 'ms')
throw new Error('npm.load() required')
throw new Error('npm.load() required')
// startup, ok to do this synchronously
var j = parseJSON(fs.readFileSync(
path.join(__dirname, '../package.json')) + '')
log.info('error reading version', ex)
var aliasNames = Object.keys(aliases)
var littleGuys = [ 'isntall', 'verison' ]
var fullList = cmdList.concat(aliasNames).filter(function (c) {
return plumbing.indexOf(c) === -1
var abbrevs = abbrev(fullList)
fullList = npm.fullList = fullList.filter(function (c) {
return littleGuys.indexOf(c) === -1
Object.keys(abbrevs).concat(plumbing).forEach(function addCommand (c) {
Object.defineProperty(npm.commands, c, { get: function () {
'Call npm.load(config, cb) before using this command.\n' +
'See the README.md or bin/npm-cli.js for example usage.'
if (c === 'la' || c === 'll') {
npm.config.set('long', true)
if (commandCache[a]) return commandCache[a]
var cmd = require(path.join(__dirname, a + '.js'))
commandCache[a] = function () {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof args[args.length - 1] !== 'function') {
if (args.length === 1) args.unshift([])
// Options are prefixed by a hyphen-minus (-, \u2d).
// Other dash-type chars look similar but are invalid.
Array(args[0]).forEach(function (arg) {
if (/^[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D]/.test(arg)) {
log.error('arg', 'Argument starts with non-ascii dash, this is probably invalid:', arg)
registryRefer = [a].concat(args[0]).map(function (arg) {
// exclude anything that might be a URL, path, or private module
// Those things will always have a slash in them somewhere
if (arg && arg.match && arg.match(/\/|\\/)) {
}).filter(function (arg) {
npm.referer = registryRefer
Object.keys(cmd).forEach(function (k) {
commandCache[a][k] = cmd[k]
enumerable: fullList.indexOf(c) !== -1,
// make css-case commands callable via camelCase as well
if (c.match(/-([a-z])/)) {
addCommand(c.replace(/-([a-z])/g, function (a, b) {
function defaultCb (er, data) {
if (er) console.error(er.stack || er.message)
npm.deref = function (c) {
c = c.replace(/([A-Z])/g, function (m) {
return '-' + m.toLowerCase()
if (plumbing.indexOf(c) !== -1) return c
loadListeners.forEach(function (cb) {
process.nextTick(cb.bind(npm, er, npm))
npm.load = function (cli, cb_) {
if (!cb_ && typeof cli === 'function') {
if (!cb_) cb_ = function () {}
if (loaded || loadErr) return cb(loadErr)
if (npm.config.get('force')) {
log.warn('using --force', 'I sure hope you know what you are doing.')
onload = onload && npm.config.get('onload-script')
log.warn('onload-script', 'failed to require onload script', onload)
log.warn('onload-script', err)
function load (npm, cli, cb) {
which(process.argv[0], function (er, node) {
if (!er && node.toUpperCase() !== process.execPath.toUpperCase()) {
log.verbose('node symlink', node)
process.installPrefix = path.resolve(node, '..', '..')
var builtin = path.resolve(__dirname, '..', 'npmrc')
npmconf.load(cli, builtin, function (er, config) {
if (er === config) er = null
// if the 'project' config is not a filename, and we're
// not in global mode, then that means that it collided
// with either the default or effective userland config
if (!config.get('global') &&
config.sources.project &&
config.sources.project.type !== 'ini') {
'Skipping project config: %s. (matches userconfig)',
config.localPrefix + '/.npmrc'
// Include npm-version and node-version in user-agent
var ua = config.get('user-agent') || ''
ua = ua.replace(/\{node-version\}/gi, process.version)
ua = ua.replace(/\{npm-version\}/gi, npm.version)
ua = ua.replace(/\{platform\}/gi, process.platform)
ua = ua.replace(/\{arch\}/gi, process.arch)
// continuous integration platforms
const ciName = process.env.GERRIT_PROJECT ? 'gerrit'
: process.env.GITLAB_CI ? 'gitlab'
: process.env.APPVEYOR ? 'appveyor'
: process.env.CIRCLECI ? 'circle-ci'
: process.env.SEMAPHORE ? 'semaphore'
: process.env.DRONE ? 'drone'
: process.env.GITHUB_ACTION ? 'github-actions'
: process.env.TDDIUM ? 'tddium'
: process.env.JENKINS_URL ? 'jenkins'
: process.env['bamboo.buildKey'] ? 'bamboo'
: process.env.GO_PIPELINE_NAME ? 'gocd'
// codeship and a few others
: process.env.CI_NAME ? process.env.CI_NAME
// test travis after the others, since several CI systems mimic it
: process.env.TRAVIS ? 'travis-ci'
// aws CodeBuild/CodePipeline
: process.env.CODEBUILD_SRC_DIR ? 'aws-codebuild'
: process.env.CI === 'true' || process.env.CI === '1' ? 'custom'
// Google Cloud Build - it sets almost nothing
: process.env.BUILDER_OUTPUT ? 'builder'
const ci = ciName ? `ci/${ciName}` : ''
ua = ua.replace(/\{ci\}/gi, ci)
config.set('user-agent', ua.trim())
if (config.get('metrics-registry') == null) {
config.set('metrics-registry', config.get('registry'))
var color = config.get('color')
if (npm.config.get('timing') && npm.config.get('loglevel') === 'notice') {
log.level = config.get('loglevel')
log.heading = config.get('heading') || 'npm'
log.stream = config.get('logstream')
npm.color = process.stdout.isTTY && process.env['TERM'] !== 'dumb'
if (config.get('unicode')) {
if (config.get('progress') && process.stderr.isTTY && process.env['TERM'] !== 'dumb') {
glob(path.resolve(npm.cache, '_logs', '*-debug.log'), function (er, files) {
while (files.length >= npm.config.get('logs-max')) {
var umask = npm.config.get('umask')
exec: parseInt('0777', 8) & (~umask),
file: parseInt('0666', 8) & (~umask),
var gp = Object.getOwnPropertyDescriptor(config, 'globalPrefix')
Object.defineProperty(npm, 'globalPrefix', gp)
var lp = Object.getOwnPropertyDescriptor(config, 'localPrefix')
Object.defineProperty(npm, 'localPrefix', lp)
config.set('scope', scopeifyScope(config.get('scope')))
npm.projectScope = config.get('scope') ||
scopeifyScope(getProjectScope(npm.prefix))
Object.defineProperty(npm, 'prefix',
return npm.config.get('global') ? npm.globalPrefix : npm.localPrefix
var k = npm.config.get('global') ? 'globalPrefix' : 'localPrefix'
Object.defineProperty(npm, 'bin',
if (npm.config.get('global')) return npm.globalBin
return path.resolve(npm.root, '.bin')
Object.defineProperty(npm, 'globalBin',
if (process.platform !== 'win32') b = path.resolve(b, 'bin')
Object.defineProperty(npm, 'dir',
if (npm.config.get('global')) return npm.globalDir
return path.resolve(npm.prefix, 'node_modules')
Object.defineProperty(npm, 'globalDir',
return (process.platform !== 'win32')
? path.resolve(npm.globalPrefix, 'lib', 'node_modules')
: path.resolve(npm.globalPrefix, 'node_modules')
Object.defineProperty(npm, 'root',
{ get: function () { return npm.dir } })
Object.defineProperty(npm, 'cache',
{ get: function () { return npm.config.get('cache') },
set: function (r) { return npm.config.set('cache', r) },
var rand = require('crypto').randomBytes(4).toString('hex')
Object.defineProperty(npm, 'tmp',
if (!tmpFolder) tmpFolder = 'npm-' + process.pid + '-' + rand
return path.resolve(npm.config.get('tmp'), tmpFolder)
// the better to repl you with
Object.getOwnPropertyNames(npm.commands).forEach(function (n) {
if (npm.hasOwnProperty(n) || n === 'config') return
Object.defineProperty(npm, n, { get: function () {
var args = Array.prototype.slice.call(arguments, 0)
if (args.length === 1 && Array.isArray(args[0])) {
if (typeof args[args.length - 1] === 'function') {
npm.commands[n](args, cb)
if (require.main === module) {
require('../bin/npm-cli.js')
function scopeifyScope (scope) {
return (!scope || scope[0] === '@') ? scope : ('@' + scope)
function getProjectScope (prefix) {
var pkg = JSON.parse(fs.readFileSync(path.join(prefix, 'package.json')))
if (typeof pkg.name !== 'string') return ''
var sep = pkg.name.indexOf('/')
if (sep === -1) return ''
return pkg.name.slice(0, sep)