Categories
Javascript

How to Read file in Node.js

Synchronously, Asynchronously and using Streams are three ways to read files in node.js
Let’s explore them in detail…

This article covers three ways to read files in Node.js

1. Reading File Synchronously.

If you want to read content of file synchronously, use fs.readFileSync(). Simply pass path and encoding method to read file content.

const fs = require('fs')
let data  = fs.readFileSync('./sample.txt', 'utf8');
console.log(data);

Try to avoid reading file synchronously as it is blocking.

2. Reading File asynchronously.

If reading file synchronously is not your concern, use fs.readFile() method.
Simply pass filePath, encoding and a callback function which will be called with the file data.

const = fs = require('fs');
fs.readFile('./sample.txt', 'utf8', (err, data) => {
    if(err) {
        console.log(err.message);
        return;
     } else {
        console.log(data)
     }
})

This is most used way to read file in Node.js. It is non-blocking and will not block the event loop.

Drawback of using readFileAsync() and readFileSync() method is that they load file all data in memory at once so if file is larger than your system memory then you will not be able to read data from file. This drawback take us to third method, Streams.

3. Using Streams

What are Streams?

Streams are methods which can handle reading/writing files, network communications, or any kind of end-to-end information exchange in an efficient way.

What makes streams more powerful, is that instead of a reading a file into memory all at once like in the traditional way, streams read chunks of data piece by piece, processing its content without keeping it all in memory.

const fs = require('fs')

const stream = fs.createReadStream('./sample.txt' , {
    encoding: 'utf8'
});


// This event is called when data is available to read in stream
stream.on('data', (data) => {
    console.log(data);
})
// This event is called when file is completely read
stream.on('end', () => {
    console.log('file is completely read');
})

// This event is called if there is error in while reading file
stream.on('error', (err) => {
    console.log(err.message);
})

fs.createReadStream() let you create Readable stream. There are two mode in stream, static and flowing mode. The stream will start with static mode. The moment you start listening to data event it will move into flowing mode and execute attached callback (In our case to read data chunk).

When there is no more data to read, stream will notify by emitting an end even.

Using streams to process smaller chunks of data, makes it possible to read larger files.

Let’s take a “streaming” services such as YouTube or Netflix for example: these services don’t make you download the video and audio feed all at once. Instead, your browser receives the video as a continuous flow of chunks, allowing the recipients to start watching and/or listening almost immediately.

Summary

In this article, we saw three way to read file content.

  • Synchronous reading of file using fs.readFileSync()
  • Asynchronous reading of file using fs.readFile().
  • Reading data in chunks using fs.createReadSteam().

Hope you have enjoyed this article. Good Luck, Happy Coding!

Let the author know what's in your mind !!

This site uses Akismet to reduce spam. Learn how your comment data is processed.