Skip to content
/ Stream/文件流
12/18/2023
1.1m
AI 摘要

本文介绍了 Node.js 中文件流的使用,包括 ReadStreamWriteStream 的功能及代码示例,强调了文件流在处理大文件时的优势,如提高速度、异步读写和管道操作,并展示了 readStream 的原型链结构。

文件流

Node.js 中的文件流主要用于文件数据的读写

ReadStream & WriteStream

利用可读流(ReadStream) 和 可写流(WriteStream) 读写文件:

import fs from 'fs'

const readStream = fs.createReadStream('child.js');

readStream.setEncoding('utf8').on('data', (chunk) => {
  // chunk 的数据
  console.log(chunk);
});

const writeStream = fs.createWriteStream('index.js')

writeStream.write('hello world')
writeStream.end()

文件流的主要优点:

  • 提高文件的读写速度,特别是大文件。
  • 可以按块处理文件,而不是等待整个文件加载完成。
  • 可以进行管道操作,将文件数据通过管道传输到其他流。
  • 异步化文件读写

结构

对于 createReadStream 创建的对象,所构建的对象关系如下图所示:

__proto__
prototype
__proto__
prototype
__proto__
prototype
readStream
fs.ReadStream.prototype
fs.ReadStream
stream.Readable.prototype
stream.Readable
evevts.EventEmitter.prototype
evevts.EventEmitter
readStream 的原型链

实际上所有的 stream 都是基于 EventEmitter 的,而 stream 也提供了一些事件被监听

Released under the MIT License.