Getting Started With Node – Course

How to Read Files

You can use fs.readFile() or fs.readFileSync() method to read files in Node.

Here is the sample data for the file.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

For example:

Using the readFile() method.

const fs = require('fs');

fs.readFile('./lorem.txt', (err, data) => {
    if(err) {
        return console.log('Error occurred while reading file');
    }
    console.log(data.toString());
});

Using the readFileSync() method.

const fs = require('fs');

const data = fs.readFileSync('./lorem.txt');

console.log(data.toString());

You can run this program using the following command.

node <file name>.js

1 Comment

Leave a Reply to Than Kywe Cancel reply

Your email address will not be published. Required fields are marked *

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