@suin/runspace
TypeScript icon, indicating that this package has built-in type declarations

2.3.0 • Public • Published

@suin/runspace

Isolated execution context for Node.js.

Installation

# via NPM
npm install --save @suin/runspace
# via Yarn
yarn add @suin/runspace

Usage

Basic usage:

// main.js
const { ThreadSpace, ChildProcessSpace } = require("@suin/runspace");

(async () => {
  const space = new ThreadSpace({ filename: "./target.js" }) // Or new ChildProcessSpace({ filename: "./target.js" })
    .on("message", (message) => console.log(message))
    .on("error", (error) => console.error(error))
    .on("rejection", (reason) => console.error(reason));

  await space.waitStart();
  space.send("Hello");
  await space.waitStop();
})();

// target.js
process.on("message", (message) => {
  process.send(message + " World");
  process.exit();
});

// Output:
// "Hello World"

Waits a message from the program inside the space:

// target.js
const http = require("http");

const server = http.createServer((req, res) => {
  res.write("OK");
  res.end();
});
server.listen(8000, () => {
  process.send("HTTP_SERVER_READY");
});

// main.js
const { ThreadSpace } = require("@suin/runspace");
const fetch = require("node-fetch");

(async () => {
  const space = new ThreadSpace({ filename: "./target.js" });
  await space.waitStart();
  await space.waitMessage((message) => message === "HTTP_SERVER_READY");
  const res = await fetch("http://localhost:8000");
  const text = await res.text();
  await space.stop();
  console.log(text); // Output: "OK"
})();

Readme

Keywords

none

Package Sidebar

Install

npm i @suin/runspace

Weekly Downloads

2

Version

2.3.0

License

MIT

Unpacked Size

109 kB

Total Files

36

Last publish

Collaborators

  • suin