示例:在 VM 中运行 HTTP Server


当使用 script.runInThisContext()vm.runInThisContext() 时,代码在当前 V8 全局上下文中执行。 传给此 VM 上下文的代码将有自己的隔离作用域。

为了使用 node:http 模块运行简单的 web 服务器,传给上下文的代码必须要么自己调用 require('node:http'),要么有对传给它的 node:http 模块的引用。 例如:

'use strict';
const vm = require('node:vm');

const code = `
((require) => {
  const http = require('node:http');

  http.createServer((request, response) => {
    response.writeHead(200, { 'Content-Type': 'text/plain' });
    response.end('Hello World\\n');
  }).listen(8124);

  console.log('Server running at http://127.0.0.1:8124/');
})`;

vm.runInThisContext(code)(require);

上述案例中的 require() 与其传入的上下文共享状态。 当执行不受信任的代码时,这可能会带来风险,例如以不需要的方式更改上下文中的对象。

When using either script.runInThisContext() or vm.runInThisContext(), the code is executed within the current V8 global context. The code passed to this VM context will have its own isolated scope.

In order to run a simple web server using the node:http module the code passed to the context must either call require('node:http') on its own, or have a reference to the node:http module passed to it. For instance:

'use strict';
const vm = require('node:vm');

const code = `
((require) => {
  const http = require('node:http');

  http.createServer((request, response) => {
    response.writeHead(200, { 'Content-Type': 'text/plain' });
    response.end('Hello World\\n');
  }).listen(8124);

  console.log('Server running at http://127.0.0.1:8124/');
})`;

vm.runInThisContext(code)(require);

The require() in the above case shares the state with the context it is passed from. This may introduce risks when untrusted code is executed, e.g. altering objects in the context in unwanted ways.