Skip to content

Read files in Node.js using callbacks

Callbacks can be used to write clean implementations of anything Promises in Node.js. This is a sample code to read files using callbacks.

const fs = require('fs');

let readDataCallback = (err, data) => {
    if (err) {
        console.log(`Something went wrong: ${err}`);
    } else {
        console.log(`Provided file contained: ${data}`);
    }
};

fs.readFile('./fileOne.txt', 'utf-8', readDataCallback);

fs.readFile('./anotherFile.txt', 'utf-8', readDataCallback);

fs.readFile('./finalFile.txt', 'utf-8', readDataCallback);
Advertisements
See also  Update all the Node dependencies to their latest version

Leave a 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.