@fastly/http-compute-js

中文文档
2.0.0发布于 2026/02/12MITTypeScriptES Module构建来源已验证近 30 天下载 7098

Node.js-compatible request and response objects for JavaScript on Fastly Compute

原始使用文档
文档目录9 节
  1. Usage
  2. Notes / Known Issues
  3. Example
  4. The server object
  5. Manual instantiation of req and res
  6. Example
  7. Issues
  8. Security issues
  9. License

@fastly/http-compute-js

A library aiming to provide Node.js-compatible request and response objects.

Compute provides Request and Response objects based on the modern Fetch standard rather than the req and res objects traditionally seen in Node.js programs. If you are more familiar with using the Node.js request and response objects, or have some libraries that work with them, this library aims to let you do that.

Usage

To your Compute JavaScript project (which you can create using npm init @fastly/create and the Compute JavaScript Empty Starter Kit), add the @fastly/http-compute-js package as a dependency.

npm install @fastly/http-compute-js

In your program:

import http from '@fastly/http-compute-js';

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!'
  }));
});

server.listen();

req and res are implementations of IncomingMessage and ServerResponse, respectively, and can be used as in a Node.js program.

req is an IncomingMessage object whose Readable interface has been wired to the body of the Compute request's body stream. As such, you can read from it using the standard on('data')/on('end') mechanisms, or using libraries such as parse-body. You can also read the headers and other information using the standard interface.

res is a ServerResponse object whose Writable interface is wired to an in-memory buffer. Write to it normally using res.write() / res.end() or pipe to it using res.pipe(). You can also set headers and status code using the standard interfaces.

Notes / Known Issues

  • The aim of this library is to provide compatibility where practical. Please understand that some features are not possible to achieve 100% compatibility with Node.js, due to platform differences.
  • The library uses npm packages such as stream-browserify, buffer, events, and process to simulate Node.js behavior for low-level objects.
  • Other libraries that consume IncomingMessage and ServerResponse may or may not be compatible with Compute. Some may work if you apply polyfills during module bundling.
  • HTTP Version is currently always reported as 1.1.
  • Unlike in Node.js, the socket property of these objects is always null, and cannot be assigned.
  • Some functionality is not (yet) supported: http.Agent, http.ClientRequest, http.get(), http.request(), to name a few.
  • Transfer-Encoding: chunked does not work at the moment and has been disabled.
  • At the current time, the ServerResponse write stream must be finished before the Response object is generated.

Example

The following is an example that reads the URL, method, headers, and body from the request, and writes a response.

import http from '@fastly/http-compute-js';

const server = http.createServer(async (req, res) => {
  // Get URL, method, headers, and body from req
  const url = req.url;
  const method = req.method;
  const headers = {};
  for (let [key, value] of Object.entries(req.headers)) {
    if(!Array.isArray(value)) {
      value = [String(value)];
    }
    headers[key] = value.join(', ');
  }
  let body = null;
  if (method !== 'GET' && method !== 'HEAD') {
    // Reading data out of a stream.Readable 
    body = await new Promise(resolve => {
      const data = [];
      req.on('data', (chunk) => {
        data.push(chunk);
      });
      req.on('end', () => {
        resolve(data.join(''));
      });
    });
  }

  // Write output to res
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    url,
    method,
    headers,
    body,
  }));
});

server.listen();

The server object

server is an instance of HttpServer, modeled after http.Server. It is created using the createServer() function, usually passing in your request handler. The server begins to listen for fetch events once the listen() function is called.

createServer([onRequest])

  • Instantiates an HttpServer instance, optionally passing in an onRequest listener.
  • Parameters:
    • onRequest - (optional) supplying this is equivalent to calling server.on('request', onRequest) after instantiation.
  • Returns: an HttpServer instance.

HttpServer class members:

  • listen([port][,onListening])
    • Starts the server listening for fetch events.
    • Parameters:
      • port - (optional) a port number. This argument is purely for API compatibility with Node's server.listen(), and is ignored by Compute.
      • onListening - (optional) supplying this is equivalent to calling server.on('listening', onListening) before calling this method.
  • event: 'listening'
    • Emitted when the fetch event handler has been established after calling server.listen().
  • event: 'request'
    • Emitted each time there is a request.
    • Parameters:
      • request - http.IncomingMessage
      • response - http.ServerResponse

Manual instantiation of req and res

Sometimes, you may need to use Node.js-compatible request and response objects for only some parts of your application. Or, you may be working with an existing application or package (for example, "middleware") designed to interact with these objects.

@fastly/http-compute-js provides utility functions that help in this case to help you go back and forth between the Request and Response objects used in Compute and their Node.js-compatible counterparts.

toReqRes(request)

  • Converts from a Compute-provided Request object to a pair of Node.js-compatible request and response objects.
  • Parameters:
    • request - A Request object. You would typically obtain this from the request property of the event object received by your fetch event handler.
  • Returns: an object with the following properties.
    • req - An http.IncomingMessage object whose Readable interface has been wired to the Request object's body. NOTE: This is an error if the Request's body has already been used.
    • res - An http.ServerResponse object whose Writable interface has been wired to an in-memory buffer.

toComputeResponse(res)

  • Creates a new Response object from the res object above, based on the status code, headers, and body that has been written to it. This Response object is typically used as the return value from a Compute fetch handler.
  • Parameters:
    • res - An http.ServerResponse object created by toReqRes().
  • Returns: a promise that resolves to a Response object.
  • NOTE: This function returns a Promise that resolves to a Response once the res object emits the 'finish' event, which typically happens when you call res.end(). If your application never signals the end of output, this promise will never resolve, and your application will likely time out.
  • If an error occurs, the promise will reject with that error.

Example

The following is an example that shows the use of the manual instantiation functions in a Compute JavaScript application written using a fetch event listener. Node.js-compatible req and res objects are produced from event.request. After having some output written, a Response object is created from the res object and returned from the event listener.

/// <reference types='@fastly/js-compute' />
import { toReqRes, toComputeResponse } from '@fastly/http-compute-js';

addEventListener('fetch', (event) => event.respondWith(handleRequest(event)));
async function handleRequest(event) {
  // Create Node.js-compatible req and res from event.request
  const { req, res } = toReqRes(event.request);

  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!'
  }));

  // Create a Compute-at-Edge Response object based on res, and return it
  return await toComputeResponse(res);
}

Issues

If you encounter any non-security-related bug or unexpected behavior, please file an issue using the bug report template.

Security issues

Please see our SECURITY.md for guidance on reporting security-related issues.

License

MIT.

In order for this library to function without requiring a direct dependency on Node.js itself, portions of the code in this library are adapted / copied from Node.js. Those portions are Copyright Joyent, Inc. and other Node.js contributors.

See the LICENSE file for details.

版本与发布记录

@fastly/http-compute-js 共发布 35 个版本,首次发布于 2022/08/06;过去 12 个月发布了 1 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.0.0latest2026/02/129 个月前
2.0.0-beta.0beta2025/05/081.5 年前
1.1.52025/01/061.9 年前
1.1.42024/01/252 年前
1.1.32024/01/252 年前
1.1.22023/11/083 年前

关于 @fastly/http-compute-js 的常见问题

@fastly/http-compute-js 是什么?

Node.js-compatible request and response objects for JavaScript on Fastly Compute

如何安装 @fastly/http-compute-js?

在项目目录运行 npm install @fastly/http-compute-js,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@fastly/js-compute(^2.0.0 || ^3.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@fastly/http-compute-js 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fastly/http-compute-js 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@fastly/http-compute-js 可以商用吗?

@fastly/http-compute-js 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fastly/http-compute-js 的下载量有多少?

根据 npm 官方下载统计,@fastly/http-compute-js 在 2026/10/15 – 2026/11/13 这 30 天内被下载 7,098 次,日均约 237 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fastly/http-compute-js 还在维护吗?

最新版本 2.0.0 发布于 2026/02/12(9 个月前);至今共发布 35 个版本,其中过去 12 个月发布了 1 个;首次发布于 2022/08/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。