UNPKG

2.59 kBJavaScriptView Raw
1var check = require('check-types');
2var spawn = require('child_process').spawn;
3var q = require('q');
4var NPM_PATH = require('npm-utils').path;
5var formInstallCommand = require('./report-install-command');
6
7// returns a promise
8function installModule(options, results) {
9 check.verify.object(options, 'missing options');
10 check.verify.string(options.name, 'expected module name string');
11 check.verify.string(options.version, 'expected version string');
12
13 if (options.keep) {
14 console.assert(typeof options.keep === 'boolean', 'invalid keep');
15 }
16 if (results) {
17 check.verify.array(results, 'missing results');
18 }
19
20 var cmd = formInstallCommand([[{
21 name: options.name,
22 version: options.version,
23 works: true
24 }]]);
25 check.verify.unemptyString(cmd, 'could not form install command');
26 cmd = cmd.trim();
27
28 var moduleVersion = options.name + '@' + options.version, npm;
29 if (options.keep) {
30 console.log(' ', cmd);
31 var args = cmd.split(' ');
32 args.shift();
33 args.push('--save-exact');
34 npm = spawn(NPM_PATH, args);
35 } else {
36 if (!options.tldr) {
37 console.log(' installing', moduleVersion);
38 }
39 npm = spawn(NPM_PATH, ['install', moduleVersion]);
40 }
41
42 var testOutput = '';
43 var testErrors = '';
44
45 npm.stdout.setEncoding('utf-8');
46 npm.stderr.setEncoding('utf-8');
47
48 function hasError(str) {
49 return /error/i.test(str);
50 }
51
52 npm.stdout.on('data', function (data) {
53 if (hasError(data)) {
54 console.log('stdout:', data);
55 }
56 testOutput += data;
57 });
58
59 npm.stderr.on('data', function (data) {
60 if (hasError(data)) {
61 console.log('stderr:', data);
62 }
63 testErrors += data;
64 });
65
66 npm.on('error', function (err) {
67 console.error('error:', err);
68 testErrors += err.toString();
69 });
70
71 var deferred = q.defer();
72 npm.on('exit', function (code) {
73 if (code) {
74 console.error('npm returned', code);
75 console.error('errors:\n' + testErrors);
76 deferred.reject({
77 code: code,
78 errors: testErrors
79 });
80 } else {
81 if (!options.tldr) {
82 console.log(moduleVersion, 'installed successfully');
83 }
84 deferred.resolve(results);
85 }
86 });
87 return deferred.promise;
88}
89
90module.exports = installModule;