📜  Node.js 中 readFile 和 createReadStream 的区别

📅  最后修改于: 2022-05-13 01:56:44.157000             🧑  作者: Mango

Node.js 中 readFile 和 createReadStream 的区别

在本文中,我们将讨论 Nodejs 中 readFile 和 createReadStream 的区别。两者都是允许我们打开文件/流并读取其中存在的数据的模块。

1. readFile : fs 模块包含 readFile 方法。它用于通过将文件带入缓冲区来读取文件。它是一种异步方法,因此,它读取文件而不阻塞代码的执行。首先,我们将 fs 模块引入我们的应用程序,然后在其中使用 readFile 方法。

句法:

fs.readFile( filename, encoding, callback_function)

参数:

  • 文件名:它保存必须读取的文件的路径。
  • encoding:它保存文件的编码。如果未指定选项,则返回原始缓冲区,默认值为 'utf8'。
  • callback_function:读取文件后调用的函数,包含两个参数err和data。如果遇到任何错误,则将其存储在 err 中,否则文件的内容将存储在数据中。

返回值:它返回文件的内容。

示例:在此示例中,我们使用 readFile 方法读取文件,要读取的文件是 output.txt。

输出.txt 文件:

This is an output file read from readFile method.
index.js
const fs = require('fs');
fs.readFile('output.txt', 'utf8', (err, data) => {
  console.log(`Data present in the file is::    ${data}`);
});
console.log('Outside readFile method');


index.js
const fs = require('fs');
const createReader = fs.createReadStream('output.txt');
  
createReader.on('data', (data) => {
  console.log(data.toString());
});
  
console.log('Outside createReader.on method');


输出:

Outside readFile method
Data present in the file is::   
This is an output file read from readFile method.

2. createReadStream fs 模块包含内置API(应用程序编程接口)createReadStream。它允许我们打开文件/流并读取其中存在的数据。

句法:

fs.createReadStream(path, options)

参数:

  • 路径:它保存必须读取的文件的路径。它可以是字符串,缓冲区的 URL。
  • options:它是一个可选参数。我们可以传递一个字符串或对象给它。
  • 返回值:返回ReadObject Stream的对象。

示例:在此示例中,我们通过 createReadStream.on 方法读取文件名 output.txt。

输出.txt 文件:

This is an output file read from createReadStream method.

index.js

const fs = require('fs');
const createReader = fs.createReadStream('output.txt');
  
createReader.on('data', (data) => {
  console.log(data.toString());
});
  
console.log('Outside createReader.on method');

输出:

Outside createReader.on method
This is an output file read from createReadStream method.

readFile 和 createReadStream 的区别:

readFile

createReadStream

It reads the file into the memory before making it available 

to the user.

It reads the file in chunks according to a need by the user.
It is slower due to read of whole file.It is faster due to its property of bringing in chunks.

It will not scale in case of too many requests as it will try to load

them all at the same time.

It is scalable as it pipes the content directly to the HTTP

response object

Due to its property, it is easier for nodejs to handle cleaning of memory in this case.

In this case memory cleaning by nodejs is not easy.