Skip to content

Commit c5f4cda

Browse files
committed
CommonJS naïve implementation
1 parent 298e11d commit c5f4cda

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

JavaScript/f-commonjs.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'use strict';
2+
3+
const fs = require('node:fs').promises;
4+
const vm = require('node:vm');
5+
6+
const RUN_OPTIONS = { timeout: 5000, displayErrors: false };
7+
8+
const pseudoRequire = (name) => {
9+
console.log(`Intercepted require: ${name}`);
10+
};
11+
12+
const load = async (filePath, sandbox) => {
13+
const src = await fs.readFile(filePath, 'utf8');
14+
const code = `(require, module, __filename, __dirname) => {\n${src}\n}`;
15+
const script = new vm.Script(code);
16+
const context = vm.createContext(Object.freeze({ ...sandbox }));
17+
const wrapper = script.runInContext(context, RUN_OPTIONS);
18+
const module = {};
19+
wrapper(pseudoRequire, module, filePath, __dirname);
20+
return module.exports;
21+
};
22+
23+
const main = async () => {
24+
const sandbox = { Map: class PseudoMap {} };
25+
const exported = await load('./1-export.js', sandbox);
26+
console.log(exported);
27+
};
28+
29+
main();

0 commit comments

Comments
 (0)