Skip to content

Node.js Files and Streams: fs/promises, JSON Files, ENOENT, readline and pipeline with gzip

NeedMyTools Academy

Sign in free to read the full lesson

Sign in or create a free account

Free forever. No card, no paywall.

Reading and writing files is the first thing a browser cannot do and Node.js can. Reports, invoices, exports from a shop system, logs and configuration all live in files. This lesson starts with the simple way, reading a whole file into memory with node:fs/promises, uses it for a JSON price list, and shows how to handle a file that does not exist yet. Then it moves to streams, which process data piece by piece: we generated a sales file with half a million rows, totalled it twice, once with streams and once by reading it whole, and compared the memory. Finally we compressed it with gzip in one line. Recorded with Node.js 22.23.4.

Quick answer

In Node.js, read a file with await readFile(path, "utf8") and write one with await writeFile(path, text) from node:fs/promises. Build paths with join(import.meta.dirname, ...) from node:path, and catch errors with err.code === "ENOENT" for missing files. For large files use streams: createReadStream with readline to go line by line, and pipeline from node:stream/promises to connect a source, a transform such as createGzip() and a destination.

40 min read and practice · Content checked on 27 November 2026

In this lesson you will

  • Read and write text and JSON files with fs/promises
  • Build file paths that work wherever the script is run from
  • Handle a missing file with the ENOENT error code
  • Process large files with streams, readline and pipeline

Reading and writing whole files

The module node:fs/promises has promise based versions of every file operation, so you can await them like fetch. readFile(path, "utf8") returns the content as a string; without the encoding you get a Buffer of raw bytes. JSON.parse turns the text of prices.json into an array of objects, and writeFile saves a string, replacing the file if it exists. Use appendFile to add to the end of a log instead, and mkdir(dir, { recursive: true }) to create folders.

Pay attention to paths. A relative path such as "data/prices.json" is resolved from the folder the terminal is in, not from the script, so the same script breaks when a scheduler runs it from another folder. import.meta.dirname is the folder of the current module, and join from node:path glues parts together with the right separator for Windows or Linux. Building paths this way makes the script work no matter where it is started.

Example: A price report from a JSON file
data/prices.json
[
  { "item": "Dates 1 kg", "price": 45 },
  { "item": "Saffron 5 g", "price": 60 },
  { "item": "Oud oil 3 ml", "price": 150 }
]
report.js
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";

const dataDir = join(import.meta.dirname, "data");
const prices = JSON.parse(await readFile(join(dataDir, "prices.json"), "utf8"));

const lines = prices.map((p) => `${p.item}: ${(p.price * 1.05).toFixed(2)} AED incl. VAT`);
await writeFile(join(dataDir, "report.txt"), lines.join("\n") + "\n");
console.log(`Wrote ${lines.length} lines to data/report.txt`);
Real output: terminal, node report.js
Wrote 3 lines to data/report.txt
Real output: terminal, cat data/report.txt
Dates 1 kg: 47.25 AED incl. VAT
Saffron 5 g: 63.00 AED incl. VAT
Oud oil 3 ml: 157.50 AED incl. VAT

The project is the souq-tools folder from lesson 2, with "type": "module" in package.json, so top level await works in .js files.

Sign in free to read the full lesson

You are reading the free preview. Create a free account (it takes one minute, no password) to unlock the rest of this lesson and track your progress.

Unlocks after sign-in:

  • 3 more sections with live code examples
  • Common mistakes to avoid
  • Hands-on coding exercise with automatic checks
  • Practice quiz and the graded lesson test
Sign in or create a free account

Free forever. No card, no paywall.

Questions people ask

Should I use readFileSync or await readFile?

In a server, use the promise version: readFileSync blocks the event loop, so every other request waits. In a small command line script that runs once, the sync versions are acceptable and sometimes simpler.

How do I read a CSV file in Node.js?

For simple files with no commas inside values, read line by line with readline and split(","), as in this lesson. Real exports often have quoted values with commas or new lines inside, so use a tested parser package such as csv-parse for those.

What is import.meta.dirname?

The absolute path of the folder that contains the current ES module, the replacement for __dirname from CommonJS. import.meta.filename is the full path of the file itself.

How do I list the files in a folder with Node.js?

Use await readdir(dir) from node:fs/promises, which returns an array of names. Add { withFileTypes: true } to tell files from folders, or { recursive: true } to include every subfolder.

Does writeFile replace the old content?

Yes. It creates the file or overwrites it completely. To add to the end, use appendFile, and to avoid a half written file after a crash, write to a temporary name and then rename it over the old one.

Sources

Facts in this lesson were checked against these official pages on 27 November 2026.

Code examples stay in English and run in a sandbox on your device. If you spot a mistake, tell us through the contact page.