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
EasyThis 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.
count.jsalready printsReading...and knows which file to read:fileis the word typed afternode count.js, ornotes.jsonwhen nothing is typed.- Read that file with
fs.readFileand a callback. Everything below happens inside the callback. - If the read worked, turn the text into an array with
JSON.parse. Print how many notes the array holds, followed bynotes. Count the notes in the array, not the lines of the file.notes.jsonstarts with two notes, so you print2 notes. - If the read failed, meaning the callback's error is not
null, printCannot readfollowed by the file name instead of the count. - In both cases, print
Donelast, also from inside the callback.
node count.js prints:
Reading...
2 notes
Donenode count.js nothere.json prints:
Reading...
Cannot read nothere.json
DoneTry 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.
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