Open In App

Difference between readFile and createReadStream in Node.js

In this article, we will discuss the difference between readFile and createReadStream in Nodejs. Both are modules that allow us to open a file/stream and read data present in it.

1. readFile: fs module contains the readFile method. It is used to read a file by bringing it into the buffer. It is an asynchronous method and due to this, it reads the file without blocking the execution of the code. First, we bring the fs module into our app then use the readFile method inside it.



Syntax:

fs.readFile( filename, encoding, callback_function)

Parameters:



Return Value: It returns the content of a file.

Example: In this example, we are reading the file using the readFile method, File to be read is output.txt.

output.txt file:

This is an output file read from readFile method.




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');

Output:

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

2. createReadStream: fs module contains the inbuilt API(Application programming interface) createReadStream.It allows us to open a file/stream and reads the data present inside it.

Syntax:

fs.createReadStream(path, options)

Parameters:

 

Example: In this example, We are reading file name output.txt by createReadStream.on method.

Output.txt file:

This is an output file read from createReadStream method.




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

Output:

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

Difference between readFile and 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.

Article Tags :