readable.toArray([options])


稳定性: 1 - 实验

  • options <Object>
    • signal <AbortSignal> 如果信号被中止,则允许取消 toArray 操作。
  • 返回: <Promise> 包含数组(如果流处于对象模式)或具有流内容的缓冲区的 promise。

此方法可以轻松获取流的内容。 如果流处于对象模式,则返回其内容的数组。 如果流不处于对象模式,则返回包含其数据的缓冲区。

由于此方法将整个流读入内存,它否定了流的好处。 它旨在实现互操作性和便利性,而不是作为消费流的主要方式。

import { Readable } from 'stream';
import { Resolver } from 'dns/promises';

await Readable.from([1, 2, 3, 4]).toArray(); // [1, 2, 3, 4]

// 使用 .map 同时进行 dns 查询
// 并使用 toArray 将结果收集到一个数组中
const dnsResults = await Readable.from([
  'nodejs.org',
  'openjsf.org',
  'www.linuxfoundation.org',
]).map(async (domain) => {
  const { address } = await resolver.resolve4(domain, { ttl: true });
  return address;
}, { concurrency: 2 }).toArray();

Stability: 1 - Experimental

  • options <Object>
    • signal <AbortSignal> allows cancelling the toArray operation if the signal is aborted.
  • Returns: <Promise> a promise containing an array (if the stream is in object mode) or Buffer with the contents of the stream.

This method allows easily obtaining the contents of a stream. If the stream is in object mode an array of its contents is returned. If the stream is not in object mode a Buffer containing its data is returned.

As this method reads the entire stream into memory, it negates the benefits of streams. It's intended for interoperability and convenience, not as the primary way to consume streams.

import { Readable } from 'stream';
import { Resolver } from 'dns/promises';

await Readable.from([1, 2, 3, 4]).toArray(); // [1, 2, 3, 4]

// Make dns queries concurrently using .map and collect
// the results into an array using toArray
const dnsResults = await Readable.from([
  'nodejs.org',
  'openjsf.org',
  'www.linuxfoundation.org',
]).map(async (domain) => {
  const { address } = await resolver.resolve4(domain, { ttl: true });
  return address;
}, { concurrency: 2 }).toArray();