[英]Issues with using “npm install” programmatically
我們可以通過編程方式使用“ npm”,這是一個了不起的功能,但是我遇到了一些問題。 函數“ npm.load”似乎沒有觸發。 我沒有在“ npm.load”或“ npm.commands.install”函數中獲得任何控制台日志。
var npm = require('npm');
// There is another promise here
.then(function(path) {
// this is working the way I intend it to
cache[requestId].package = JSON.parse(path);
// This is firing
if (cache[requestId].package.name && cache[requestId].package.version && cache[requestId].package.scripts.start) {
// console logs and an array [ 'keystone', 'async', 'underscore', 'swig', 'node-sass', 'node-sass-middleware', 'dotenv' ]
console.log(Object.keys(cache[requestId].package.dependencies));
// console logs as /Users/207004/Desktop/github/mothership/server/app/routes/tractor-beam/ms-apps/my_site
console.log(localPath);
// console logs as a [Function]
console.log(npm.load);
// *** Here is the issue! This is not firing! ***
npm.load({}, function(err) {
// no console log
console.log(npm.commands.install);
// no console log
console.log(err);
npm.commands.install(localPath, Object.keys(cache[requestId].package.dependencies), function(err, done) {
// no console log
console.log('loaded');
// no console log
console.log(err, done);
// I am assuming that this is not firing, but my code does fire the console log in the next promise
return PM2.connectAsync();
});
});
} else {
console.log('else');
}
})
// Another promise chained here. A console log inside of this promise is firing.
任何幫助,將不勝感激。 請讓我知道,如果你有任何問題。
謝謝,
我花了幾天的時間,但我想出了很多。
這是我想出的解決方案,它帶有承諾:
var Promise = require('bluebird');
// This will create promise functions for all the methods in the "child_process" module.
// Created "exec.execAsync" below.
var exec = Promise.promisifyAll(require('child_process'));
// Function to make package names one long string for the command line.
var getDependencies = function(dependencies) {
var deps = '';
Object.keys(dependencies).forEach(function(el){
deps = deps + ' ' + el;
});
return deps;
};
// Promise before this reads the package.json file
.then(function(packageJson){
var deps;
var pack = JSON.parse(packageJson);
if(pack && pack.dependencies) {
deps = getDependencies(pack.dependencies);
// I used the "--prefix" flag because I wanted to install the dependencies in a different directory.
// This part takes a while. Plan your promises before and after accordingly.
// The command below console logs into this "npm install --prefix /Users/Max/Desktop/github/mothership/server/app/routes/tractor-beam/ms-apps/my_site keystone async underscore swig node-sass node-sass-middleware dotenv"
return exec.execAsync('npm install --prefix ' + localPath + deps);
}
})
// Continues to next promise
如果您有任何疑問,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.