A Promise Result
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 19 of 33.
A promise represents a result that will arrive later. Unlike the callback version from node:fs, readFile from node:fs/promises takes no callback and returns a promise. Its .then method accepts a function to call with the result when the read succeeds.
import { readFile } from 'node:fs/promises';
readFile('name.txt', 'utf8').then((name) => {
console.log('Hello, ' + name);
});The name parameter holds the file text, not a promise. Work that depends on the text belongs here. For now the file is provided and the read succeeds. The following step will handle a read that fails.
Challenge
EasyRun practice.js first: it prints Note: [object Promise]. The program is combining text with the promise instead of its eventual result.
Use a .then callback to print the completed read as Note: followed by the file text. No argument reads note.txt, giving Note: Buy milk. Try other.txt: expect Note: Call Ada.
Try it yourself
import { readFile } from 'node:fs/promises';
const file = process.argv[2] ?? 'note.txt';
console.log('Note: ' + readFile(file, 'utf8'));
All lessons in Node.js Basics
Practice on your own: Express playground