Reading and Writing Files

Node's fs/promises module reads a whole text file with readFile, saves one with writeFile, adds to one with appendFile, and reports a missing file with the error code ENOENT, which your code can catch and explain.

Apprentice · Node.js · JavaScript · Updated

By

After this lesson you can

  • Read and write text files with readFile, writeFile and appendFile from node:fs/promises, using utf8
  • Catch the ENOENT error when a file isn't there, and report it with a message a person can act on

Key takeaways

  • readFile from node:fs/promises reads a whole file. Give it "utf8" to get text back; without it, you get a Buffer of raw bytes.
  • writeFile creates a file or replaces everything in it, and appendFile adds to the end of a file, creating it when it isn't there.
  • The fs/promises functions return promises, so await each one. Without await, you get Promise { <pending> } instead of the text.
  • When a file isn't there, readFile throws an error whose code is ENOENT. Catch it, check error.code, and tell the person what to fix.

Most command-line tools you'll write at work follow the same pattern: read a file, work something out, write the answer. A script that tidies a spreadsheet export, a build tool that reads its settings, a server that loads its configuration when it starts: each one reads and writes files. A web page can't touch the files on your computer (imagine any website reading your documents), but a Node program can, because you chose to run it.

This chapter's example is the Trailhead Running Club. Its coach, Dana, keeps every run in a file named runs.csv, and on Sunday nights she adds up each runner's week by hand. By the end of the chapter, a command does it for her.

Reading a whole file: readFile

Node's built-in module node:fs/promises (fs, read "F-S", is short for file system) holds the file functions. Make a folder named running-club, with a package.json that holds { "type": "module" } and this runs.csv:

date,runner,miles,minutes
2026-11-02,Maya,4.0,38
2026-11-02,Leo,3.1,31
2026-11-03,Priya,5.0,45
2026-11-04,Maya,6.2,60

Then read.js, in the same folder:

import { readFile } from "node:fs/promises";

const text = await readFile("runs.csv", "utf8");
console.log(text);

Run it with node read.js:

date,runner,miles,minutes
2026-11-02,Maya,4.0,38
2026-11-02,Leo,3.1,31
2026-11-03,Priya,5.0,45
2026-11-04,Maya,6.2,60

readFile takes the file's name and gives back a promise of its whole contents. await waits for it; in an ES module, await works at the top level, outside any function.

The second argument, "utf8" (read "U-T-F eight"), names the file's text encoding: the code that says which number stands for which letter. With it, you get text. Leave it out, and you get a Buffer, the file's raw bytes as numbers:

import { readFile } from "node:fs/promises";

const data = await readFile("runs.csv");
console.log(data);
<Buffer 64 61 74 65 2c 72 75 6e 6e 65 72 2c 6d 69 6c 65 73 2c 6d 69 6e 75 74 65 73 0a 32 30 32 36 2d 31 31 2d 30 32 2c 4d 61 79 61 2c 34 2e 30 2c 33 38 0a 32 ... 68 more bytes>

64 is the letter d, 61 is a, and so on. Raw bytes are right for a picture; for text, pass "utf8".

One more mistake worth knowing by sight: forget await, and console.log shows the promise, not the text, because the reading hasn't finished yet:

Promise { <pending> }

Writing and adding: writeFile and appendFile

writeFile creates a file, or replaces everything in it when it's already there. appendFile adds to the end, and creates the file first when it isn't there. Each line of text needs its own \n (read "new line") at the end.

import { writeFile, appendFile, readFile } from "node:fs/promises";

await writeFile("week.txt", "Week of November 2\n");
await appendFile("week.txt", "Maya: 10.2 miles\n");
await appendFile("week.txt", "Leo: 3.1 miles\n");

console.log(await readFile("week.txt", "utf8"));
Week of November 2
Maya: 10.2 miles
Leo: 3.1 miles

Run it twice, and week.txt still has three lines: writeFile starts the file fresh each time, then the two appendFile calls add to it. That same power is a danger: writeFile("runs.csv", ...) would wipe Dana's whole log. When you mean "add a line", use appendFile.

When the file isn't there: ENOENT

Mistype the name, or run the program from the wrong folder, and readFile can't find the file. It throws an error, which try and catch can catch:

import { readFile } from "node:fs/promises";

try {
  const text = await readFile("run.csv", "utf8");
  console.log(text);
} catch (error) {
  console.log(error.code);
}
ENOENT

ENOENT (read "E-NO-ENT", short for error: no entry) is Node's code for "there's no file or folder at that path". The error's message says the same with the full path it tried, such as ENOENT: no such file or directory, open 'C:\Users\Sam\nodejs-course\running-club\run.csv'. Without the try, that message and a stack trace stop the program.

A person running your tool doesn't need a stack trace. They need to know what's wrong and what to do about it. Check error.code, and answer an ENOENT with a message they can act on:

import { readFile } from "node:fs/promises";

async function readLog(fileName) {
  try {
    return await readFile(fileName, "utf8");
  } catch (error) {
    if (error.code === "ENOENT") {
      console.log(`Can't find ${fileName}. Check its name, and that you're in the folder that holds it.`);
      return "";
    }
    throw error;
  }
}

const text = await readLog("run.csv");
console.log(`Read ${text.length} characters.`);
Can't find run.csv. Check its name, and that you're in the folder that holds it.
Read 0 characters.

The throw error matters: any other error, such as EACCES (permission denied), still stops the program, because a message about a missing file would send the person looking for the wrong problem. Arguments, Exit Codes and Clear Errors shows where error messages should go, and how to tell the computer that ran your program that it failed.

Check yourself

2 questions to try on the lesson page.

So what

Read, work it out, write: with readFile, writeFile, appendFile and a clear message for ENOENT, you have the first and last steps of every command-line tool you'll build.

Key terms

Related