Skip to content

Commit

Permalink
Provide workaround if running without ESM support
Browse files Browse the repository at this point in the history
  • Loading branch information
Alhadis committed Oct 5, 2018
1 parent 94a40a3 commit bdfe576
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
4 changes: 2 additions & 2 deletions bin/html-tty
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env node
"use strict";

new Promise(resolve => {
require("../lib/adapters/esm.js")(() => new Promise(resolve => {
const fs = require("fs");
if(process.argv[2])
resolve(fs.readFileSync(process.argv[2], "utf8"));
Expand Down Expand Up @@ -38,4 +38,4 @@ new Promise(resolve => {
}).catch(error => {
console.error(error);
process.exit(1);
});
}));
38 changes: 38 additions & 0 deletions lib/adapters/esm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Hack for executables needing an entry-point into an ESM graph.
*
* Executes the given handler only if the current process appears
* to be running with ESM support enabled. Otherwise, a new process
* is forked with Node's `--experimental-modules` flag set.
*
* @param {Function} handler
* @internal
*/
module.exports = handler => {
"use strict";

// Raise an exception for Node versions older than v8.5.0
const [major, minor] = process.version.replace(/^\v/, "").split(".").map(Number);
if(major < 8 || 8 === major && minor < 5){
console.error("This program requires Node.js v8.5.0 or later.");
process.exit(1);
}

// ESM support enabled
const opts = (process.env.NODE_OPTIONS || "").split(/\s+/).filter(Boolean);
if(-1 !== opts.indexOf("--experimental-modules"))
return handler();

// ESM unsupported; perform a hacky workaround
const {spawn} = require("child_process");
const proc = spawn("node", process.argv.slice(1), {
stdio: ["inherit", "inherit", "pipe"],
env: Object.assign({}, process.env, {
NODE_OPTIONS: (process.env.NODE_OPTIONS || "") + " --experimental-modules",
}),
});
proc.stderr.on("data", data => {
data = String(data).replace(/^.*ExperimentalWarning: The ESM module loader is experimental.*\n/m, "");
process.stderr.write(data);
});
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
},
"engines": {
"atom": ">=1.19.0",
"node": ">=7.6.0",
"node": ">=8.5.0",
"electron": ">=1.6.0",
"chrome": ">=55",
"edge": ">=15",
Expand Down

0 comments on commit bdfe576

Please sign in to comment.