通过异步迭代简化Node.js流程

来源:岁月联盟 编辑:猪蛋儿 时间:2020-01-29
writable.end();
await finished(writable);
流水线技术(可读、可写):
import * as stream from 'stream';
import * as fs from 'fs';
const pipeline = util.promisify(stream.pipeline);
async function writeIterableToFile(iterable, filePath) {
  const readable = stream.Readable.from(
    iterable, {encoding: 'utf8'});
  const writable = fs.createWriteStream(filePath);
  await pipeline(readable, writable); // (A)
}
await writeIterableToFile(
  ['One', ' line of text./n'], 'tmp/log.txt');
// ···
我们使用以下模式(A行):
await pipeline(readable, writable);
还有readable .prototype.pipe(),但是该方法有一个警告(如果可读对象发出错误,那么可写的就不会自动关闭),但stream.pipeline() 就没有这样的警告。
与流程相关的功能
模块操作系统:
const EOL: string(since 0.7.8)
包含当前平台使用的行尾字符序列。
模块缓冲区:
Buffer.isEncoding(encoding: string): boolean (since 0.9.1)
如果编码正确地为文本指定一个受支持的Node.js编码,则返回true。支持的编码包括:
'utf8'
'utf16le'
'ascii'
'latin1
'base64'
'hex'
模块流程:
Readable.prototype[Symbol.asyncIterator](): AsyncIterableIterator (since 10.0.0)
可读流程是异步可迭代的,例如,你可以在asyc函数或异步生成器中使用For -await-of循环来遍历它们。
finished(stream: ReadableStream | WritableStream | ReadWriteStream, callback: (err?: ErrnoException | null) => void): () => Promise (since 10.0.0)
当读取/写入完成或出现错误时,返回的承诺将被解决。
这个承诺的版本是这样创建的:
const finished = util.promisify(stream.finished);
pipeline(...streams: Array): Promise(since 10.0.0)
流程之间的流水线技术,当流水线技术完成或出现错误时,将解决返回的承诺。
这个承诺的版本是这样创建的:
const pipeline = util.promisify(stream.pipeline);
Readable.from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable (since 12.3.0)
将迭代器转换为可读的流程:
interface ReadableOptions {
  highWaterMark?: number;
  encoding?: string;
  objectMode?: boolean;
  read?(this: Readable, size: number): void;
  destroy?(this: Readable, error: Error | null,
    callback: (error: Error | null) => void): void;
  autoDestroy?: boolean;
}
这些选项与可读构造函数的选项相同,并在此处进行了说明。
模块fs:
createReadStream(path: string | Buffer | URL, options?: string | {encoding?: string; start?: number}): ReadStream (since 2.3.0)
该模块为创建可读的流程提供了更多的选择:
createWriteStream(path: PathLike, options?: string | {encoding?: string; flags?: string; mode?: number; start?: number}): WriteStream(since 2.3.0)
通过选项.flags,你可以指定是否要写入还是要追加,并对文件在存在或不存在时发生的情况进行快速处理。
 

上一页  [1] [2] [3]