readable.filter(fn[, options])
稳定性: 1 - 实验
fn<Function> | <AsyncFunction> 从流中过滤块的函数。data<any> 来自流的数据块。options<Object>signal<AbortSignal> 如果流被销毁则中止,允许提前中止fn调用。
options<Object>concurrency<number> 一次调用流的最大并发调用fn。 默认值:1。signal<AbortSignal> 如果信号被中止,则允许销毁流。
- 返回: <Readable> 使用谓词
fn过滤的流。
此方法允许过滤流。
对于流中的每个块,将调用 fn 函数,如果它返回真值,则该块将被传给结果流。
如果 fn 函数返回 promise,则该 Promise 将被 await。
import { Readable } from 'node:stream';
import { Resolver } from 'node:dns/promises';
// 使用同步谓词。
for await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {
console.log(chunk); // 3, 4
}
// 使用异步谓词,单次最多进行 2 个查询。
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) {
// 在解析的 dns 记录上记录超过 60 秒的域。
console.log(result);
}Stability: 1 - Experimental
fn<Function> | <AsyncFunction> a function to filter chunks from the stream.data<any> a chunk of data from the stream.options<Object>signal<AbortSignal> aborted if the stream is destroyed allowing to abort thefncall early.
options<Object>concurrency<number> the maximum concurrent invocation offnto call on the stream at once. Default:1.signal<AbortSignal> allows destroying the stream if the signal is aborted.
- Returns: <Readable> a stream filtered with the predicate
fn.
This method allows filtering the stream. For each chunk in the stream the fn
function will be called and if it returns a truthy value, the chunk will be
passed to the result stream. If the fn function returns a promise - that
promise will be awaited.
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);
}