流消费者的 API


🌐 API for stream consumers

几乎所有的 Node.js 应用,无论多么简单,都会以某种方式使用流。下面是一个在 Node.js 应用中使用流的示例,该应用实现了一个 HTTP 服务器:

🌐 Almost all Node.js applications, no matter how simple, use streams in some manner. The following is an example of using streams in a Node.js application that implements an HTTP server:

const http = require('node:http');

const server = http.createServer((req, res) => {
  // `req` is an http.IncomingMessage, which is a readable stream.
  // `res` is an http.ServerResponse, which is a writable stream.

  let body = '';
  // Get the data as utf8 strings.
  // If an encoding is not set, Buffer objects will be received.
  req.setEncoding('utf8');

  // Readable streams emit 'data' events once a listener is added.
  req.on('data', (chunk) => {
    body += chunk;
  });

  // The 'end' event indicates that the entire body has been received.
  req.on('end', () => {
    try {
      const data = JSON.parse(body);
      // Write back something interesting to the user:
      res.write(typeof data);
      res.end();
    } catch (er) {
      // uh oh! bad json!
      res.statusCode = 400;
      return res.end(`error: ${er.message}`);
    }
  });
});

server.listen(1337);

// $ curl localhost:1337 -d "{}"
// object
// $ curl localhost:1337 -d "\"foo\""
// string
// $ curl localhost:1337 -d "not json"
// error: Unexpected token 'o', "not json" is not valid JSON 

Writable 流(例如示例中的 res)提供了诸如 write()end() 等方法,用于向流中写入数据。

Readable 流使用 EventEmitter API 来通知应用代码当有数据可以从流中读取时。这些可用的数据可以通过多种方式从流中读取。

WritableReadable 流都以各种方式使用 EventEmitter API 来传达流的当前状态。

🌐 Both Writable and Readable streams use the EventEmitter API in various ways to communicate the current state of the stream.

DuplexTransform 流都是 WritableReadable

向流写入数据或从流读取数据的应用不需要直接实现流接口,通常也没有理由调用 require('node:stream')

🌐 Applications that are either writing data to or consuming data from a stream are not required to implement the stream interfaces directly and will generally have no reason to call require('node:stream').

希望实现新类型流的开发者应参考第流实现者的 API节。

🌐 Developers wishing to implement new types of streams should refer to the section API for stream implementers.