Typorithm · easy

fs read & write

fs-readwritenodejsfspromisesencoding
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn fs read & write

0%

File System & Streams

node:fs/promises gives you async readFile and writeFile that return promises you await. Pass "utf8" to read text as a string; without an encoding you get a Buffer. The sync variants (readFileSync) block the event loop.

node:fs/promises is the idiomatic async file API: readFile and writeFile return promises, so you await them without blocking other work.

The second argument to readFile is the encoding. Pass "utf8" to get back a decoded string; omit it and you receive a raw Buffer of bytes.

The synchronous counterparts — readFileSync, writeFileSync — return directly but freeze the entire event loop until disk I/O finishes, so reserve them for startup or scripts.

01

readFile and writeFile from node:fs/promises return promises.

02

Pass "utf8" to read/write strings; without it you get a Buffer.

03

The Sync variants block the event loop — avoid them in servers.

import { readFile, writeFile } from "node:fs/promises";
const text = await readFile("a.txt", "utf8");
await writeFile("b.txt", text);

Read the implementation

Connect each part of the code to the concept before you type.

1. Promises API import

The node:fs/promises module exposes async, promise-returning versions of the file system calls.

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

2. Await a read

readFile returns a promise; await suspends until the file is loaded without blocking the event loop.

const text = await readFile("a.txt", "utf8");

3. Encoding argument

Passing "utf8" decodes the bytes into a string; omit it and you get a raw Buffer instead.

"utf8"

4. Write the file

writeFile creates or overwrites the file with the given contents and resolves when the write completes.

await writeFile("b.txt", text);

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

fs read & write: Lesson & Practice · Typorithm | ApplyDjinn