2015-09-18 2 views
1

Это потрясающая функция, которую мы можем использовать «npm программно», но я сталкиваюсь с некоторыми проблемами. Функция «npm.load», похоже, не срабатывает. Я не получаю никаких консольных журналов, которые находятся внутри моих функций «npm.load» или «npm.commands.install».Проблемы с использованием программ «npm 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. 

Любая помощь будет оценена по достоинству. Пожалуйста, дай мне знать, если возникнут какие-либо вопросы.

Спасибо,

ответ

0

Мне потребовались несколько дней, но я многое решил.

  1. Пока я работал над этим, кажется, что documentation for using npm programmatically был удален с сайта npmjs.com. Не уверен, что это означает, что они устарели для модуля, но я решил использовать «child_process» после того, как обнаружил, что документация удалена.
  2. Когда я заявил выше, что «npm.load» и «npm.install» не стреляли, причина заключалась в том, что у меня было приложение для узлов, работающее с npm «nodemon». Каждый раз, когда я запускаю «load» или «install», nodemon будет рассматривать это изменение в каталоге, и мое приложение перезапустится. Я столкнулся с той же проблемой с «child_process». Очень глупо! Я знаю!
  3. С моим решением, приведенным ниже, требуется некоторое время для запуска программы npm для программного программирования, поэтому планируйте соответственно.

Вот решение, которое я придумал, и это с обещаниями:

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 

Позвольте мне знать, если у вас есть какие-либо вопросы.