當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Node.js stream.Readable.filter(fn[, options])用法及代碼示例


readable.filter(fn[, options])

添加於:v17.4.0、v16.14.0
Stability: 1 - 實驗性

參數

此方法允許過濾流。對於流中的每個塊,將調用fn 函數,如果它返回一個真值,則該塊將被傳遞給結果流。如果fn 函數返回一個promise - 該promise 將是await ed。

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

// With a synchronous predicate.
for await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {
  console.log(chunk); // 3, 4
}
// With an asynchronous predicate, making at most 2 queries at a time.
const resolver = new Resolver();
const dnsResults = Readable.from([
  'nodejs.org',
  'openjsf.org',
  'www.linuxfoundation.org',
]).filter(async (domain) => {
  const { address } = await resolver.resolve4(domain, { ttl: true });
  return address.ttl > 60;
}, { concurrency: 2 });
for await (const result of dnsResults) {
  // Logs domains with more than 60 seconds on the resolved dns record.
  console.log(result);
}

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 stream.Readable.filter(fn[, options])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。