Callbacks
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 14 of 24.
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
Easycount.jsprintsReading..., then<n> notesfrom inside the callback, thenDone, also from the callback.- When the file cannot be read, it prints
Cannot read <file>instead of the count.
Run node count.js, then node count.js nothere.json.
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
1Running JavaScript on Node
Hello, NodeCommand-Line ArgumentsCommandsPractice on your own: Express playground