exports.install = function (projectPath, packageName, save, dev) {
const npm = 'npm'
const args = ['install']
args.push(packageName)
if (save) args.push('--save')
if (dev) args.push('--save-dev')
var ls = require('child_process').spawn(npm, args, {
// stdio: 'inherit',
cwd: projectPath
})
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data)
})
ls.stderr.on('data', function (err) {
console.log('stderr: ' + err)
})
ls.once('close', function () {
console.log('install success...')
})
}
执行npm命令,会报以下的错
报错原因:在windows下npm的执行名不同
解决方法:
var ls = require('child_process').spawn(process.platform === 'win32' ? 'npm.cmd' : npm, args, {
// stdio: 'inherit',
cwd: projectPath
})
packageUtil.test.js
'use strict'
const path = require('path')
const packageUtil = require('../dist/packageUtil')
const p = path.resolve(__dirname, '..')
/**执行npm install koa-markdown --save-dev**/
packageUtil.install(p, 'koa-markdown', true, true)
/**执行npm install koa-markdown --save**/
packageUtil.install(p, 'koa-markdown', true, false)