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);

echo "Buy milk" > notes.txt

node main.js

Buy milk

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");

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);

2

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);

empty

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

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which read is a good fit for a small startup file?

    Answer

    readFileSync with the utf8 encoding

    A small file read once at startup is simple with the sync call, and utf8 returns text.

  2. What does writeFileSync do when the file already exists?

    Answer

    It replaces the content of the file

    The call creates the file when absent and replaces it when present.

  3. Which pair stores an object in a text file and reads it back?

    Answer

    JSON.stringify on write and JSON.parse on read

    stringify turns the object into text, and parse turns the text back into a value.

  4. Why check existsSync before a read in a startup script?

    Answer

    A missing file throws, and absence is a normal case with a default

    The guard turns a crash into a friendly default, though a server should handle the error instead.

  5. What does this program print? import { writeFileSync, readFileSync } from "node:fs"; writeFileSync("note.txt", "Buy milk", "utf8"); const text: string = readFileSync("note.txt", "utf8"); console.log(text);

    Answer

    Buy milk

    The write creates the file, and the read returns its text.

  6. What does this program print? import { writeFileSync } from "node:fs"; const tags: string[] = ["ts", "node"]; writeFileSync("tags.json", JSON.stringify(tags), "utf8"); const back = JSON.parse("[\"ts\", \"node\"]") as string[]; console.log(back.length);

    Answer

    2

    The parsed array holds two strings, so its length is 2.

  7. What does this program print? import { existsSync } from "node:fs"; console.log(existsSync("definitely-missing.txt"));

    Answer

    false

    The check reports whether the file exists, and this one does not.

  8. What does this program print? console.log(JSON.parse("{\"a\":1}").a);

    Answer

    1

    The parsed object has the key a with the value 1.

  9. What does the compiler say about this program? import { readFileSync } from "node:fs"; const text: string = readFileSync("notes.txt"); console.log(text);

    Answer

    error TS2322: Type 'NonSharedBuffer' is not assignable to type 'string'.

    Without an encoding the read returns bytes, and the call must name utf8 to return text.

  10. What does the compiler say about this program? const tags: string[] = ["ts", 1]; console.log(tags);

    Answer

    error TS2322: Type 'number' is not assignable to type 'string'.

    Every element of a string array must be a string, and 1 is a number.

Article author: Arthur Isaev