filehandle.pullSync([...transforms][, options])


稳定性: 1 - 实验性

  • ...transforms <Function> | <Object> 可通过 stream/iter pullSync() 应用的可选转换。
  • options <Object>
    • autoClose <boolean> 当流结束时关闭文件句柄。 默认值: false
    • start <number> 开始读取的字节偏移量。指定后,读取将使用显式定位。默认值: 当前文件位置。
    • limit <number> 在结束迭代器之前要读取的最大字节数。**默认:**读取直到文件结尾(EOF)。
    • chunkSize <number> 为每次读取操作分配的缓冲区大小(字节)。默认值: 131072(128 KB)。
  • 返回:Iterable

filehandle.pull() 的同步对应方法。返回一个同步可迭代对象,使用主线程上的同步 I/O 读取文件。读取操作以 chunkSize 字节块(默认 128 KB)执行。

🌐 Synchronous counterpart of filehandle.pull(). Returns a sync iterable that reads the file using synchronous I/O on the main thread. Reads are performed in chunkSize-byte chunks (default 128 KB).

在可迭代对象被消费的过程中,文件句柄被锁定。与异步 pull() 不同,此方法不支持 AbortSignal,因为所有操作都是同步的。

🌐 The file handle is locked while the iterable is being consumed. Unlike the async pull(), this method does not support AbortSignal since all operations are synchronous.

此功能仅在启用 --experimental-stream-iter 标志时可用。

🌐 This function is only available when the --experimental-stream-iter flag is enabled.

import { open } from 'node:fs/promises';
import { textSync, pipeToSync } from 'node:stream/iter';
import { compressGzipSync, decompressGzipSync } from 'node:zlib/iter';

const fh = await open('input.txt', 'r');

// Read as text (sync)
console.log(textSync(fh.pullSync({ autoClose: true })));

// Sync compress pipeline: file -> gzip -> file
const src = await open('input.txt', 'r');
const dst = await open('output.gz', 'w');
pipeToSync(src.pullSync(compressGzipSync(), { autoClose: true }), dst.writer({ autoClose: true }));const { open } = require('node:fs/promises');
const { textSync, pipeToSync } = require('node:stream/iter');
const { compressGzipSync, decompressGzipSync } = require('node:zlib/iter');

async function run() {
  const fh = await open('input.txt', 'r');

  // Read as text (sync)
  console.log(textSync(fh.pullSync({ autoClose: true })));

  // Sync compress pipeline: file -> gzip -> file
  const src = await open('input.txt', 'r');
  const dst = await open('output.gz', 'w');
  pipeToSync(
    src.pullSync(compressGzipSync(), { autoClose: true }),
    dst.writer({ autoClose: true }),
  );
}

run().catch(console.error);