Menu
CoddyTech

Waiting for a Value

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

An await expression lets you write the next step after the read, instead of inside a then callback. It waits for this promise and gives you its result. Other work can still run while the read is waiting.

const text = await readFile('name.txt', 'utf8');
console.log(text.toUpperCase());

Without await, text would hold the promise, which has no string methods. These files are modules, so await is allowed outside a function. Inside a function, mark the function async. An async function also returns a promise to its caller.

challenge icon

Challenge

Easy

Run practice.js first. The error says text.toUpperCase is not a function: text holds a promise, not the file text.

Make text hold the completed read before the program uses it. Keep the asynchronous file function. Run again: the output is BUY MILK.

Run with the argument other.txt: the supplied second file must print CALL ADA. Keep the supplied filename expression.

Try it yourself

import { readFile } from 'node:fs/promises';
const text = readFile(process.argv[2] ?? 'note.txt', 'utf8');
console.log(text.toUpperCase());

All lessons in Node.js Basics

Practice on your own: Express playground