项目作者: suin

项目描述 :
Isolated execution context for Node.js.
高级语言: TypeScript
项目地址: git://github.com/suin/runspace.git
创建时间: 2020-10-05T14:04:52Z
项目社区:https://github.com/suin/runspace

开源协议:MIT License

下载


@suin/runspace

Isolated execution context for Node.js.

Installation

```shell script

via NPM

npm install —save @suin/runspace

via Yarn

yarn add @suin/runspace

  1. ## Usage
  2. Basic usage:
  3. ```javascript
  4. // main.js
  5. const { ThreadSpace, ChildProcessSpace } = require("@suin/runspace");
  6. (async () => {
  7. const space = new ThreadSpace({ filename: "./target.js" }) // Or new ChildProcessSpace({ filename: "./target.js" })
  8. .on("message", (message) => console.log(message))
  9. .on("error", (error) => console.error(error))
  10. .on("rejection", (reason) => console.error(reason));
  11. await space.waitStart();
  12. space.send("Hello");
  13. await space.waitStop();
  14. })();
  15. // target.js
  16. process.on("message", (message) => {
  17. process.send(message + " World");
  18. process.exit();
  19. });
  20. // Output:
  21. // "Hello World"

Waits a message from the program inside the space:

  1. // target.js
  2. const http = require("http");
  3. const server = http.createServer((req, res) => {
  4. res.write("OK");
  5. res.end();
  6. });
  7. server.listen(8000, () => {
  8. process.send("HTTP_SERVER_READY");
  9. });
  10. // main.js
  11. const { ThreadSpace } = require("@suin/runspace");
  12. const fetch = require("node-fetch");
  13. (async () => {
  14. const space = new ThreadSpace({ filename: "./target.js" });
  15. await space.waitStart();
  16. await space.waitMessage((message) => message === "HTTP_SERVER_READY");
  17. const res = await fetch("http://localhost:8000");
  18. const text = await res.text();
  19. await space.stop();
  20. console.log(text); // Output: "OK"
  21. })();