ProgramGuru

Reading and Writing Files

Reading and Writing Files — why it matters

The node:fs/promises API provides asynchronous filesystem operations such as readFile and writeFile. Pass encodings when you want text; otherwise a read returns bytes. Handle missing files and permissions errors and prefer a controlled path when writing application data.

What you’ll learn

  • Explain reading and writing files and the problem it solves.
  • Identify the relevant compile-time checks and runtime responsibilities.
  • Run the example, predict its output, and try a realistic modification.

Understand the mechanism

mkdtemp creates a unique temporary directory; writeFile stores the text; readFile returns a string with utf8 encoding. The finally block removes created files, including if an operation fails.

Avoid writing to fixed shared paths in examples; temporary directories prevent overwriting a user's real files.

Follow the concept flow

Reading and Writing Files — concept flowTemp directory → Write and read UTF-8 → Clean upReading and Writing Files1Temp directory2Write and read UTF-83Clean upBrowser code needs browser APIs; Node code needs Node.js APIs.
Follow the responsibilities from input to checked result.

Run the primary TypeScript example

Save as reading-writing-files.ts. The following program passed strict TypeScript compilation, and the displayed output was captured by executing its emitted JavaScript with Node.js 22.16.0.

TypeScript source

import { mkdtemp, writeFile, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
async function main(): Promise<void> {
  const dir = await mkdtemp(join(tmpdir(), "ts-course-"));
  try {
    const file = join(dir, "message.txt");
    await writeFile(file, "Read carefully", "utf8");
    console.log(await readFile(file, "utf8"));
  } finally { await rm(dir, { recursive: true, force: true }); }
}
main().catch(console.error);

Verified output

Read carefully

Compile: npx tsc --strict --target es2022 --module commonjs reading-writing-files.ts; run: node reading-writing-files.js. For Node.js API examples, install @types/node first. For browser projects, use the browser-specific instructions below.

The example runs in Node.js 22.16.0; if it reads runtime environment details, your displayed values may differ.

Trace the result

mkdtemp creates a unique temporary directory; writeFile stores the text; readFile returns a string with utf8 encoding. The finally block removes created files, including if an operation fails.

Predict what changes if you alter one input. Then run the code to compare your reasoning with the real output.

Common mistake and correction

Avoid writing to fixed shared paths in examples; temporary directories prevent overwriting a user's real files.

Identify whether the failure is a type-checking issue, a configuration issue, or a runtime behavior issue before choosing a fix.

Practice the concept

Write JSON representing a task list to a temporary file, read it back, and parse it using JSON.parse.

Write down your expected result first. For configuration examples, compare compiler output and diagnostics; for test examples, make the assertion fail deliberately to verify that the tool reports it.

Check your understanding

Which statement best describes the role of TypeScript and the actual runtime for this lesson?
Choose one answer. You can try again.

Answer and explanation

The described check or API works only within its stated environment and still needs the corresponding runtime behavior.

mkdtemp creates a unique temporary directory; writeFile stores the text; readFile returns a string with utf8 encoding. The finally block removes created files, including if an operation fails.

What to remember

The node:fs/promises API provides asynchronous filesystem operations such as readFile and writeFile.

Run the primary example, then complete the practice task or environment-specific lab.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Working with Paths and Directories →