-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathf-commonjs.js
More file actions
29 lines (23 loc) · 843 Bytes
/
f-commonjs.js
File metadata and controls
29 lines (23 loc) · 843 Bytes
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
'use strict';
const fs = require('node:fs').promises;
const vm = require('node:vm');
const RUN_OPTIONS = { timeout: 5000, displayErrors: false };
const pseudoRequire = (name) => {
console.log(`Intercepted require: ${name}`);
};
const load = async (filePath, sandbox) => {
const src = await fs.readFile(filePath, 'utf8');
const code = `(require, module, __filename, __dirname) => {\n${src}\n}`;
const script = new vm.Script(code);
const context = vm.createContext(Object.freeze({ ...sandbox }));
const wrapper = script.runInContext(context, RUN_OPTIONS);
const module = {};
wrapper(pseudoRequire, module, filePath, __dirname);
return module.exports;
};
const main = async () => {
const sandbox = { Map: class PseudoMap {} };
const exported = await load('./1-export.js', sandbox);
console.log(exported);
};
main();