UNPKG

parallel-park

Version:

Parallel/concurrent async work, optionally using multiple processes

67 lines (66 loc) 2.34 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const fs_1 = __importDefault(require("fs")); const vm_1 = __importDefault(require("vm")); const make_module_env_1 = __importDefault(require("make-module-env")); const debug_1 = __importDefault(require("debug")); const read_until_end_1 = require("./read-until-end"); const path_1 = __importDefault(require("path")); const debug = (0, debug_1.default)("parallel-park:child-process-worker"); const commsIn = fs_1.default.createReadStream( // @ts-ignore null, { fd: 3 }); const commsOut = fs_1.default.createWriteStream( // @ts-ignore null, { fd: 4 }); debug("reading input data..."); (0, read_until_end_1.readUntilEnd)(commsIn) .then((data) => { debug("parsing input data..."); try { const [inputs, fnString, callingFile] = JSON.parse(data); onReady(inputs, fnString, callingFile); } catch (err) { onError(err); } }) .catch(onError); function onReady(inputs, fnString, callingFile) { debug("in onReady %o", { inputs, fnString, callingFile }); // Relevant when callingFile is eg. "REPL2" (from Node.js repl) if (!path_1.default.isAbsolute(callingFile)) { callingFile = path_1.default.join(process.cwd(), "fake-path.js"); } const wrapperFn = vm_1.default.runInThisContext(`(function moduleWrapper(exports, require, module, __filename, __dirname) { return ${fnString};})`); const env = (0, make_module_env_1.default)(callingFile); const fn = wrapperFn(env.exports, env.require, env.module, env.__filename, env.__dirname); const result = fn(inputs); if (typeof result === "object" && result != null && typeof result.then === "function") { result.then(onSuccess, onError); } else { onSuccess(result); } } function onSuccess(data) { debug("in onSuccess %o", { data }); commsOut.end(JSON.stringify({ type: "success", data })); } function onError(error) { debug("in onError %o", { error }); commsOut.end(JSON.stringify({ type: "error", error: { name: error.name, message: error.message, stack: error.stack, }, })); }