Nodejs eval require path fix
frdel committed
Nov 19, 2024 at 11:05 UTC
41dc7ae14651c9a2291b79cda7e92b0bbaac3ce7
1 file changed
+24
-4
docker/exe/fs/exe/node_eval.js
+24
-4
@@ -2,11 +2,29 @@
2
3
const vm = require('vm');
4
const path = require('path');
5
+const Module = require('module');
6
6
-// Create a comprehensive context with all important global objects
7
+// Enhance `require` to search CWD first, then globally
8
+function customRequire(moduleName) {
9
+ try {
10
+ // Try resolving from CWD's node_modules
11
+ const cwdPath = path.resolve(process.cwd(), 'node_modules', moduleName);
12
+ return require(cwdPath);
13
+ } catch (cwdErr) {
14
+ try {
15
+ // Try resolving as a global module
16
+ return require(moduleName);
17
+ } catch (globalErr) {
18
+ console.error(`Cannot find module: ${moduleName}`);
19
+ throw globalErr;
20
+ }
21
+ }
22
+}
23
+
24
+// Create the VM context
25
const context = vm.createContext({
26
...global,
9
- require: require,
27
+ require: customRequire, // Use the custom require
28
__filename: path.join(process.cwd(), 'eval.js'),
29
__dirname: process.cwd(),
30
module: { exports: {} },
@@ -19,10 +37,12 @@ const context = vm.createContext({
37
setImmediate: setImmediate,
38
clearTimeout: clearTimeout,
39
clearInterval: clearInterval,
22
- clearImmediate: clearImmediate
40
+ clearImmediate: clearImmediate,
41
});
42
43
+// Retrieve the code from the command-line argument
44
const code = process.argv[2];
45
+
46
const wrappedCode = `
47
(async function() {
48
try {
@@ -38,4 +58,4 @@ vm.runInContext(wrappedCode, context, {
58
filename: 'eval.js',
59
lineOffset: -2,
60
columnOffset: 0,
41
-}).catch(console.error);
\ No newline at end of file
61
+}).catch(console.error);