Node.js Reading Text File using fs.readFile()

Using Node.js built-in file system fs module to read a text file.

Creating sample text file

Firstly creating a sample text file named sample.txt on the same directory of your Node.js code with below content.

Welcome to toricode.com

Happy Coding!


Reading file with utf8 encoding option

Below are example code how to read a text file using fs.readFile() method with utf8 encoding option and log it to the console.

let fs = require('fs');

fs.readFile('sample.txt', 'utf8', function(err, data) {
    if(err){
        console.log('ERROR!');
        console.log(err);
    } else {
        console.log(data);
    }
});

Save code above to read_file.js file and execute the code.

D:\ToriCode\Nodejs> node read_file.js
Welcome to toricode.com

Happy Coding!


Reading file without encoding option

The data will be returned as Buffer if the readFile() using without encoding option.

let fs = require('fs');

fs.readFile('sample.txt',  function(err, data) {
    if(err){
        console.log('ERROR!');
        console.log(err);
    } else {
        console.log(data);
    }
});
Execute the code.
node read_file.js
<Buffer 57 65 6c 63 6f 6d 65 20 74 6f 20 74 6f 72 69 63 6f 64 65 2e 63 6f 6d 0d 0a 0d 0a 48 61 70 70 79 20 43 6f 64 69 6e 67 21>

To read text data we can use toString() method for the return data Buffer.

let fs = require('fs');

fs.readFile('sample.txt',  function(err, data) {
    if(err){
        console.log('ERROR!');
        console.log(err);
    } else {
        console.log(data.toString());
    }
});
Execute the code.
node read_file.js
Welcome to toricode.com

Happy Coding!