Node.js File System

Read and write files with fs.

✍️ 2 exercises in this lesson

The fs module works with files. Prefer the promise-based API:

  • import { readFile, writeFile, appendFile, unlink } from "node:fs/promises";
  • await writeFile("notes.txt", "text")
  • await readFile("notes.txt", "utf8")
  • mkdir, readdir, stat, rm

The path module builds paths that work on every OS: path.join(dir, "file.txt").

Key Takeaways: Node.js File System

Mastering Node.js File System helps you write clean and reliable Node.js code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Node.js File System Code Example

Node.js
import { writeFile, appendFile, readFile, unlink } from "node:fs/promises";
import path from "node:path";

const file = path.join(process.cwd(), "notes.txt");

await writeFile(file, "Learn Node\n");
await appendFile(file, "Build APIs\n");
const text = await readFile(file, "utf8");

console.log(text.trim().split("\n"));
await unlink(file);
Output
[ 'Learn Node', 'Build APIs' ]
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Node.js File System Practice Exercises

Check what you learned in “Node.js File System”.

/ 2 solved
Fill in the blank

Read a file as text with the promise API.

const text = await readFile("notes.txt", "");
✓ Correct! Not quite. Try again.
Multiple choice

Which module builds file paths that work on every OS?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services