readable.toArray([options])


稳定性: 1 - 实验

  • options <Object>
    • signal <AbortSignal> 如果信号被中止,则允许取消 toArray 操作。
  • 返回: <Promise> 包含流内容数组的 promise。

此方法可以轻松获取流的内容。

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

import { Readable } from 'node:stream';
import { Resolver } from 'node: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 with the contents of the stream.

This method allows easily obtaining the contents of a stream.

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 'node:stream';
import { Resolver } from 'node: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();