New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Node.js› Reading and Writing Files

Reading and Writing Files

💻 Node.js

Work with text and JSON files using the promises API.

Lesson 3 of 9 Tutorial
0 of 9 completed

Node can read configuration, logs and data files. The promises API keeps asynchronous file work readable.

By the end of this lesson you can:
  • Read a text file.
  • Write and append files.
  • Read and write JSON safely.

Read

Use readFile with the utf8 encoding to get a string rather than a buffer.

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

try {
  const text = await readFile("notes.txt", "utf8");
  console.log(text);
} catch (error) {
  console.error("Could not read notes.txt:", error.message);
}

Write and Append

writeFile replaces the file. appendFile adds to the end, which is useful for logs.

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

await writeFile("output.txt", "First line\n");
await appendFile("output.txt", "Second line\n");

JSON

Read the file, parse it, and handle a parse error rather than crashing.

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

async function loadConfig() {
  try {
    const text = await readFile("config.json", "utf8");
    return JSON.parse(text);
  } catch (error) {
    if (error.code === "ENOENT") return {};
    throw error;
  }
}

const config = await loadConfig();
await writeFile("config.json", JSON.stringify(config, null, 2));
Warning Never build a file path by joining raw user input. It can escape your data folder. Validate names and use path.join with a fixed base.

Practice

  1. Read a text file and print the number of lines.
  2. Append a timestamp to a log file.
  3. Load JSON settings and provide defaults when the file is missing.

Hands-on exercise

Write a script that reads notes.txt and prints how many lines it contains.
If the file is missing, print 'No notes file found.'

Recap

The promises API makes file work readable. Handle missing files deliberately and never trust user paths.

Example

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

try {
  const text = await readFile("notes.txt", "utf8");
  console.log(text);
} catch (error) {
  console.error("Could not read notes.txt:", error.message);
}

Exercises

Exercise 1. Line counter Medium
Write a script that reads notes.txt and prints how many lines it contains.
If the file is missing, print 'No notes file found.'
Node.js exercise-1.txt
Expected Output
Line count, or a friendly message when the file is missing.

Lesson Nav

Lesson sections