示例:在虚拟机中运行 HTTP 服务器


【Example: Running an HTTP server within a VM】

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

【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.】

为了使用 node:http 模块运行一个简单的网页服务器,传递给上下文的代码必须自己调用 require('node:http'),或者被传递对 node:http 模块的引用。例如:

【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); 

上例中的 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.】