Files with fs

readFileSync

The sync read is ideal for small startup files. Pass utf8 to get text back directly instead of raw bytes.

import { readFileSync } from "node:fs"; const text: string = readFileSync("notes.txt", "utf8"); console.log(text);

Use this pattern for configs and templates under a few hundred kilobytes. Large or frequent reads deserve async methods covered later.

writeFileSync

The sync write creates the file when absent and replaces its content when present. Keep payloads small and writes infrequent, as with reads.

import { writeFileSync } from "node:fs"; writeFileSync("notes.txt", "Buy milk", "utf8"); console.log("saved");

JSON round-trip

Text files often store JSON, so stringify on write and parse on read. The pair keeps objects readable on disk and typed in memory.

import { readFileSync, writeFileSync } from "node:fs"; const tags: string[] = ["ts", "node"]; writeFileSync("tags.json", JSON.stringify(tags), "utf8"); const back = JSON.parse(readFileSync("tags.json", "utf8")) as string[]; console.log(back.length);

Exists checks

Reading a missing file throws, so check first when absence is normal. A short guard turns a crash into a friendly default.

import { existsSync, readFileSync } from "node:fs"; const text: string = existsSync("notes.txt") ? readFileSync("notes.txt", "utf8") : "empty"; console.log(text);

This check has a tiny race window, which is fine for startup scripts. Network servers should handle errors instead of pre-checking.

Next: path and os

Article author: Arthur Isaev

Banner image