-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
68 lines (54 loc) · 1.79 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
const path = require('path');
const fs = require('fs');
const requireNative = require('./lib/require-native');
const defaultLocalPath = path.join(process.env.HOME, '.nexe_natives');
function getPathToNodeModules(mainPath) {
if (path.resolve(mainPath).endsWith('node_modules')) {
return mainPath;
}
const parent = path.dirname(mainPath);
// if reached root of fs
if (parent === mainPath) {
throw Error('could not find node_modules');
}
return getPathToNodeModules(parent);
}
function getPathToPackageJson(mainPath) {
try {
const list = fs.readdirSync(mainPath);
if (list.includes('package.json')) {
return path.join(mainPath, 'package.json');
}
} catch (err) {
// ignore
}
const parent = path.dirname(mainPath);
// if reached root of fs
if (parent === mainPath) {
throw Error('could not find package.json');
}
return getPathToPackageJson(parent);
}
module.exports = (mainPath, opts = {}) => {
const externalModulesDir = opts.localPath || defaultLocalPath;
const internalModulesDir = getPathToNodeModules(mainPath);
const removeOnExit = (typeof opts.removeOnExit !== 'boolean' || opts.removeOnExit);
// parse package.json for module name
// eslint-disable-next-line
const moduleName = require(getPathToPackageJson(mainPath)).name;
if (removeOnExit) {
process.on('exit', () => {
try {
const moduleDir = path.join(externalModulesDir, moduleName);
fs.rmdirSync(moduleDir, { recursive: true });
const list = fs.readdirSync(externalModulesDir);
if (list.length === 0) {
fs.rmdirSync(externalModulesDir, { recursive: true });
}
} catch (err) {
// ignore error when deleting
}
});
}
return requireNative(moduleName, internalModulesDir, externalModulesDir);
};