Fake CommonJS system

node v10.16.3
version: 2.0.0
const files = { "print.js": `\ function print(x) { console.log(__filename, x); }; exports.print = print; `, "main.js": `\ const { print } = require("print.js"); print("Hello world"); ` };
Pretend this is the filesystem of .js files
const modules = {};
This is where the files go when they're loaded as actual JS code
function load(name) { // Modules can only be loaded once. We save the values here. if (modules[name]) { return modules[name]; } // Set up all the arguments... in a real CommonJS system there's more info here const require = load; const exports = {}; const __filename = name; const func = Function("require", "exports", "__filename", files[name]); // Run the module code func(require, exports, __filename); // Save and return the exports object modules[name] = exports; return exports; }
This is basically the `require` function, but I gave it the name `load` so it seemed less magical
This is where you would load the file specified on the command line (e.g. `main.js` in the command `node main.js`)
You can look at the modules objects here

no comments

    sign in to comment