-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (60 loc) · 1.97 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict';
const path = require('path'),
fs = require('fs'),
rimraf = require('rimraf'),
exec = require('child_process').exec,
keys = Object.keys || require('object-keys');
function reinstall(PACKAGE_JSON, dir, callback) {
const DEPS = PACKAGE_JSON.dependencies && keys(PACKAGE_JSON.dependencies) || [],
DEV_DEPS = PACKAGE_JSON.devDependencies && keys(PACKAGE_JSON.devDependencies) || [],
OPT_DEPS = PACKAGE_JSON.optionalDependencies && keys(PACKAGE_JSON.optionalDependencies) || [];
exec('cd ' + dir + ' && npm install ' + DEPS.concat(DEV_DEPS).concat(OPT_DEPS).join(' '), function(err, stdout, stderr) {
if (err) {
callback(err);
return;
}
callback(null);
console.log('\nYay! Dependencies reinstalled from scratch.');
});
}
exports.execute = function(targetDir, callback) {
targetDir = targetDir || './';
const data = fs.readFileSync(path.resolve(targetDir + '/package.json'));
if (!data) {
throw 'No package.json in ' + path.resolve(targetDir);
}
const PACKAGE_JSON = JSON.parse(data),
NODE_MODULES = path.resolve(targetDir + '/node_modules');
fs.stat(NODE_MODULES, function(err, stats) {
if (err) {
var reinstalled = false;
switch (err.code) {
case 'ENOENT':
// node_modules doesn't exist: just reinstall
reinstall(PACKAGE_JSON, path.resolve(targetDir), callback);
reinstalled = true;
break;
}
if (!reinstalled) {
callback(err);
}
return;
}
console.log('Removing existing dependencies...');
// call rm -rf on the NODE_MODULES dir
rimraf(NODE_MODULES, function(err) {
if (err) {
// TODO: error handling?
// switch (err.code) {
// case 'ENOENT':
// console.log('');
// break;
// }
console.log(err);
callback(err);
return;
}
reinstall(PACKAGE_JSON, path.resolve(targetDir), callback);
});
});
};