forked from juliangruber/require-rebuild
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (66 loc) · 2.1 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 spawnSync = require('cross-spawn').sync;
var extend = require('extend');
var Module = require('module');
var resolveSync = require('resolve').sync;
var dirname = require('path').dirname;
var join = require('path').join;
var relative = require('path').relative;
var sep = require('path').sep;
var home = require('user-home');
var mismatchRe = /Module version mismatch/;
var winRe = /A dynamic link library \(DLL\) initialization routine failed/;
var gypHome = join(home, '.node-gyp');
module.exports = patch;
function patch(opts){
var load = Module._load;
Module._load = function(request, parent){
var ret;
try {
ret = load.call(Module, request, parent);
} catch (err) {
if (!mismatchRe.test(err.message) && !winRe.test(err.message)) throw err;
var resolved = resolveSync(request, {
basedir: dirname(parent.id),
extensions: ['.js', '.json', '.node']
});
var segs = resolved.split(sep);
var path = segs.slice(0, segs.indexOf('node_modules') + 2).join(sep)
|| process.cwd();
console.error('Recompiling %s...', relative(process.cwd(), path));
// prebuild or node-gyp
var pkg = require(join(path, 'package.json'));
var reg = /prebuild/;
var prebuild = pkg.scripts
&& (reg.test(pkg.scripts.install) || reg.test(pkg.scripts.prebuild));
var ps;
if (prebuild) {
var bin = join(require.resolve('prebuild'), '../bin.js');
ps = spawnSync(bin, [
'--install',
'--abi=' + process.versions.modules,
'--target=' + process.versions.node
], {
cwd: path,
stdio: 'inherit'
});
} else {
ps = spawnSync('node-gyp', [
'rebuild',
'--target=' + process.versions.node
], {
cwd: path,
env: extend(process.env, {
'HOME': gypHome,
'USERPROFILE': gypHome
}),
stdio: 'inherit'
});
}
if (ps.error) throw ps.error;
console.error('Done!');
return load.call(Module, request, parent);
}
return ret;
};
return require;
}