In FileSystem We Believe

E.Y.
2 min readJun 3, 2020

A short recap about fs.readFile(), fs.readFileSync() and fs.createReadStream()

Photo by Maksym Kaharlytskyi on Unsplash
//FS short for file system, is a powerful built-in module in Node.const fs = require('fs');

Every fs method has both a synchronous and an asynchronous version with the name for the synchronous version adding “Sync”. So an asynchronous fs.readFile() becomes fs.readFileSync().

fs.readFileSync()

fs.readFileSync( path, options )

path: It takes the relative path of the file.

options: It is an optional parameter which contains the encoding and flag, the encoding contains data specification like 'utf8'. It’s default value is null which returns raw buffer and the flag contains indication of operations in the file. It’s default value is ‘r’.

let data = fs.readFileSync('./home/file.json', 'utf8');

fs.readFile()

fs.readFile( path, options, cb )

Comparing to the sync one, fs.readFile takes a callback :

fs.readFile('./home/file.json', 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});

What is really happening at the back of the scene, readFileSync() is converted from readFileSync()

var fs = require('fs');
function readFileAsSync(){
new Promise((resolve, reject)=>{
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
resolve(data);
});
});
}
async function callRead(){
let data = await readFileAsSync();
console.log(data);
}
callRead();

fs.createReadStream()

fs.createReadStream( path, options)

This one allows you to open up a readable stream.The response objects are also streams that you can easily pipe into to another file e.g. a HTTP response body.

What’s the difference with other methods then? While the fs.readFile()loads the whole file into the memory you pointed out, fs.createReadStream() reads the entire file in chunks of sizes that you specified( it has a default highWaterMark of 64 kb). The client will also receive the data faster with fs.createReadStream()since it can be read while it’s been processing.

So when processing big file, fs.createReadStream() is more scalable.

--

--