Skip to content

Instantly share code, notes, and snippets.

@benjie
Created December 1, 2018 15:36
Show Gist options
  • Select an option

  • Save benjie/c11ceaa819211859dcc938a3f6bf88a9 to your computer and use it in GitHub Desktop.

Select an option

Save benjie/c11ceaa819211859dcc938a3f6bf88a9 to your computer and use it in GitHub Desktop.
/*
* Read a file manually, but pretend it's actually a Node.js module. Tested in Node 8.11.3 only.
*/
"use strict";
const fs = require("fs");
const path = require("path");
const { Module } = require("module");
// Get the javascript contents from wherever: filesystem, database, network, etc.
// Node calls this filename, but it's actually the full path to the file
const filename = path.resolve("./dist/index.js");
const contents = fs.readFileSync(filename, "utf8");
// Technically you should call `stripBOM(...)` on this, but it wasn't necessary in my case.
const code = /*stripBOM(*/ contents /*)*/;
// Construct the module
const replacementModule = new Module(filename, this);
// And initialise it:
// Ref: https://github.com/nodejs/node/blob/eb6741b15ebd93ffdd71e87cbc1350b9e94ef222/lib/internal/modules/cjs/loader.js#L616
replacementModule.filename = filename;
replacementModule.paths = Module._nodeModulePaths(path.dirname(filename));
replacementModule._compile(code, filename);
replacementModule.loaded = true;
// Finally replace our exports with the manually imported file
module.exports = replacementModule.exports;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment