Promises
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 21 of 33.
Callbacks inside callbacks get hard to follow, and each one must remember to check err.
node:fs/promises returns a promise instead: an object standing for a result that arrives later. .then(fn) runs with the result, .catch(fn) runs if any step before it failed, and .finally(fn) runs either way.
import { readFile } from 'node:fs/promises';
readFile('poem.txt', 'utf8')
.then((text) => console.log(text.length + ' characters'))
.catch(() => console.log('No poem today'))
.finally(() => console.log('Bye'));An error thrown inside .then lands in .catch too, so one handler covers the read and the parsing. A promise that fails with no .catch crashes the program.
Challenge
EasyThis step opens the course’s prepared notes command-line tool project, rather than your project files from Callbacks (including count.js). Your earlier work stays in its own lesson. Read the supplied files before editing count.js. This copy contains the asynchronous notes counting example.
- Rewrite
count.jswithreadFilefromnode:fs/promisesand.then. - A missing file now prints
No notes yet, from a.catch. Donestill comes last, from.finally.
Run node count.js, then node count.js nothere.json.
With no argument, the output is Reading..., 2 notes, then Done, each on its own line. With nothere.json, the middle line is No notes yet.
Try it yourself
import fs from 'node:fs';
const file = process.argv[2] ?? 'notes.json';
console.log('Reading...');
fs.readFile(file, 'utf8', (err, text) => {
if (err) {
console.log(`Cannot read ${file}`);
} else {
console.log(`${JSON.parse(text).length} notes`);
}
console.log('Done');
});
All lessons in Node.js Basics
Practice on your own: Express playground