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
EasyRun 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
1Running JavaScript on Node
Hello, NodeReading the CommandCommand-Line ArgumentsCommands4Asynchronous Node
Using a Callback ResultCallbacksA Promise ResultWhen a Promise FailsPromisesWaiting for a ValueAsync and AwaitTwo Independent ReadsPromise.allThe Event LoopTimersPractice on your own: Express playground