Node.js - How to read file in Node.js using fs module

Node.js

Next →

In this tutorial we will learn to read file in Node.js using fs module.

The fs module

The fs module helps in interacting with the file system.

All the File System operations are available in synchronous, callback and promise-based forms.

Read file synchronously

To read the file synchronously we use the readFileSync method.

It takes two parameters.

  • path - This is the file path that we want to read.
  • options - This is an optional parameter. It contains encoding and flag.

For encoding we can take value like utf8.

The flag takes value like r, r+. Default is r which is to open the file for reading. An exception occurs if file does not exists.

In the following example we are trying to read the content of example.txt file using its full path. Also, the encoding is set to utf8.

const fs = require('fs');

console.log('Start reading...');

const data = fs.readFileSync('/Users/yusufshakeel/node-project/example.txt', { encoding: 'utf8' });

console.log('Content:');

console.log(data);

console.log('Done reading!');

The above program will console log the content of the example.txt file.

Output:

Start reading...
Content:
Hello World
Done reading!

Error handling when reading file in sync

We can wrap the read logic inside try-catch block to handle error if it occurs.

The following code will throw error as the file does not exists.

const fs = require('fs');

console.log('Start reading...');

try {
    const data = fs.readFileSync('/Users/yusufshakeel/node-project/not-found.txt', { encoding: 'utf8' });
    
    console.log('Content:');
    console.log(data);
     
    console.log('Done reading!');
} catch (e) {
    console.log('ERROR!');
    console.log(e.message);
}

Output:

Start reading...
ERROR!
ENOENT: no such file or directory, open '/Users/yusufshakeel/node-project/not-found.txt'

ENOENT is abbreviation of Error NO ENTry.

The readFilSync will block the thread. Better to use readFile as it is non blocking.

Read file asynchronously

To read file asynchronously we use the readFile method.

It takes three parameters.

  • path - This is the file path that we want to read.
  • options - This holds the encoding. Default utf8.
  • callback - This is the callback function that has two parameters err, data.

In the following example we are reading the content of a file like we did earlier.

const fs = require('fs');

console.log('Start reading...');

fs.readFile('/Users/yusufshakeel/node-project/example.txt', 'utf8', (err, data) => {
    if (err) {
        console.log('ERROR!');
        console.log(err.message);
    } else {
        console.log('Content:');
        console.log(data);
    }
});

console.log('Done reading!');

In the above example we are reading content of file example.txt and in utf8 encoding. The err will hold the error if there is any. And data will hold the content of the file.

Output:

Start reading...
Done reading!
Content:
Hello World

Since readFile is async, the content will get printed later and 'Done reading!' will be printed first.

In the above code we are using ES6 arrow function syntax.

Error handling when reading file in async

If the file does not exists then we will get error.

const fs = require('fs');

console.log('Start reading...');

fs.readFile('/Users/yusufshakeel/node-project/not-found.txt', 'utf8', (err, data) => {
    if (err) {
        console.log('ERROR!');
        console.log(err.message);
    } else {
        console.log('Content:');
        console.log(data);
    }
});

console.log('Done reading!');

Output:

Start reading...
Done reading!
ERROR!
ENOENT: no such file or directory, open '/Users/yusufshakeel/node-project/not-found.txt'

Reading file using promises

The fs.promises API provides async file system methods that returns Promise object rather than callbacks.

In this case we use .then to handle data when promise gets resolved and .catch to handle error when promise gets rejected.

const fs = require('fs').promises;

console.log('Start reading...');

fs.readFile('/Users/yusufshakeel/node-project/example.txt', 'utf8')
  .then(data => {
      console.log('Content:');
      console.log(data);
  })
  .catch(e => {
      console.log('ERROR!');
      console.log(e.message);
  });

console.log('Done reading!');

The above code will print the following output.

Start reading...
Done reading!
Content:
Hello World

So, in the above code we read the content of the file example.txt.

When the promise resolves the .then part gets executed. The data parameter holds the content of the file which we then console log.

If the promise gets rejected then the .catch part gets executed. The e parameter holds the error and we print that out.

Next →

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT