Skip to content
Justice Tech School

File System

The fs module reads and writes files. Use the promise version (fs/promises) with await for modern code. readFile, writeFile, appendFile, readdir and unlink cover most needs. Always handle errors.

Example
const fs = require("fs/promises");
const os = require("os");
const path = require("path");
(async () => {
  const file = path.join(os.tmpdir(), "node_demo.txt");
  await fs.writeFile(file, "line 1\n");
  await fs.appendFile(file, "line 2\n");
  const text = await fs.readFile(file, "utf8");
  console.log(text.trim().split("\n"));
  await fs.unlink(file);
  try { await fs.readFile(file); } catch (e) { console.log(e.code); }
})();

Result

[ 'line 1', 'line 2' ]
ENOENT

Exercise

Read a file as text.

await fs.readFile(file, "")

Quiz Test

What does err.code ENOENT mean?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.