Menu
CoddyTech

Using a Callback Result

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

A file read can finish after the next line of your program has already run. A callback is a function handed to another function to call later. readFile calls yours when the file is ready. It passes an error first and the file text second.

readFile('greeting.txt', 'utf8', (err, text) => {
    if (err) return;
    console.log(text);
});

Put work that needs the text inside this function. Outside it, the text has not arrived. The starter supplies the import and an error branch; focus on using the successful result.

challenge icon

Challenge

Easy

Run practice.js first. It fails because text is still undefined when the last line runs; the file read has not finished.

Move the work that needs the file text to the point where the read has finished. Print the contents in uppercase, keeping the error branch. Remove the outer text variable when it is no longer needed. With no argument, expect BUY MILK. With other.txt, expect CALL ADA.

Try it yourself

import { readFile } from 'node:fs';
const file = process.argv[2] ?? 'note.txt';
let text;
readFile(file, 'utf8', (err, contents) => {
    if (err) return;
    text = contents;
});
console.log(text.toUpperCase());

All lessons in Node.js Basics

Practice on your own: Express playground