Menu
CoddyTech

Callbacks

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 18 of 33.

Reading a large file takes time, and a program that sits waiting for it does nothing else meanwhile.

fs.readFile(path, 'utf8', callback) starts the read and returns at once. When the file is loaded, Node calls your callback with (err, text). err is null on success and an error otherwise, so check it first. Everything that needs the text goes inside the callback.

import fs from 'node:fs';

fs.readFile('poem.txt', 'utf8', (err, text) => {
    if (err) {
        console.log('No poem today');
        return;
    }
    console.log(text.split('\n').length + ' lines');
});
console.log('Asked for the poem');

Asked for the poem prints first: the line after readFile runs while the file is still loading.

challenge icon

Challenge

Easy

This lesson opens a fresh callback counting example in count.js, rather than your notes-tool files from Handling Errors. The supplied notes.json, notes.js and store.js are included; your earlier work stays saved in its own lesson.

Reading a big file takes time. With a callback, Node can do other work meanwhile and calls your code back when the file is ready. Practise this in a small separate program, count.js, that counts the notes in a file.

  1. count.js already prints Reading... and knows which file to read: file is the word typed after node count.js, or notes.json when nothing is typed.
  2. Read that file with fs.readFile and a callback. Everything below happens inside the callback.
  3. If the read worked, turn the text into an array with JSON.parse. Print how many notes the array holds, followed by notes. Count the notes in the array, not the lines of the file. notes.json starts with two notes, so you print 2 notes.
  4. If the read failed, meaning the callback's error is not null, print Cannot read followed by the file name instead of the count.
  5. In both cases, print Done last, also from inside the callback.

node count.js prints:

Reading...
2 notes
Done

node count.js nothere.json prints:

Reading...
Cannot read nothere.json
Done

Try it: this lesson runs count.js, so the terminal shows $ node count.js. Press Run with the box empty, and the program reads notes.json. Then type nothere.json in the box and press Enter, to read a file that does not exist.

Try it yourself

import fs from 'node:fs';

const file = process.argv[2] ?? 'notes.json';

console.log('Reading...');
// Read the file with fs.readFile and a callback.
// Print the number of notes, then Done.
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Node.js Basics

Practice on your own: Express playground