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.
-
Which read is a good fit for a small startup file?
Answer
readFileSyncwith theutf8encodingA small file read once at startup is simple with the sync call, and utf8 returns text.
-
What does
writeFileSyncdo 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.
-
Which pair stores an object in a text file and reads it back?
Answer
JSON.stringifyon write andJSON.parseon readstringify turns the object into text, and parse turns the text back into a value.
-
Why check
existsSyncbefore 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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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