-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (59 loc) · 2.14 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
68
69
70
71
72
73
74
var fs = require('fs'),
path = require('path'),
http = require('http'),
exec = require('child_process').exec;
var LOG_PREFIX = '[autoupdate]: ';
var pkg = (function find(dir) {
var pkg = path.join(dir, 'package.json'),
parent;
if (fs.existsSync(pkg)) {
return JSON.parse(fs.readFileSync(pkg, 'utf8')||{});
}
parent = path.join(dir, '../');
if (parent === dir) {
throw new Error('package.json not found');
}
return find(parent);
}(path.dirname(module.parent.filename)));
module.exports = function (callback) {
var registry = (pkg.publishConfig && pkg.publishConfig.registry) || 'http://registry.npmjs.org',
pkgUrl = registry + '/' + pkg.name;
http.get(pkgUrl, function (res) {
var data = [] ;
if (res.statusCode !== 200) {
return error(new Error('response statusCode: '+ res.statusCode));
}
res.on('data', function (chunk) {
data.push(chunk);
});
res.on('end', function () {
var command,latest;
try{
lastest = JSON.parse(Buffer.concat(data).toString())['dist-tags']['latest'] ;
}catch(err){
return error(err);
}
if (latest == pkg.version) {
console.log(LOG_PREFIX + 'You are currently on the latest version (%s)', pkg.name);
return callback(null, lastest);
}
command = 'npm install ' + pkg.name + '@' + latest + ' --registry=' + registry ;
console.log(LOG_PREFIX + 'New version found (%s@%s)', pkg.name, latest);
exec(command, function (err) {
if (err) {
return error(err);
}
console.log(LOG_PREFIX + 'Updated to %s (%s)', latest, pkg.name);
callback(null, lastest);
});
});
res.on('error',function (err){
error(err);
});
});
function error(err){
console.error(LOG_PREFIX + 'Failed to update the new version (%s)', pkg.name);
console.error(err && err.message);
callback(err);
}
};