Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 133 ยท File System

Reading and Writing Files

Learn to read and write files in Node.js with fs/promises - readFile, writeFile, appendFile, encodings, flags, FileHandle, error codes such as ENOENT and EEXIST, and atomic writes that never leave half a file.

Almost every real program touches files: configuration, logs, uploads, caches, exports, databases. Node.js ships a complete file system module called fs, and its most pleasant form is node:fs/promises, where every operation returns a promise you can await. This lesson covers the everyday operations (read, write, append), how encodings and flags change their behaviour, what the errors mean, the lower-level FileHandle, and how to write a file so a crash can never leave it half-finished.

All examples run in our editor's sandbox, where the current directory is writable but empty at the start and thrown away after the run. Files you create in one run do not exist in the next, so each example creates what it needs. On your own computer the same code reads and writes real files in whatever folder you start Node.js from.

Importing the promise API

Import what you need from node:fs/promises. The node: prefix makes it explicit that this is a built-in module and not an npm package with the same name.

NODE
import { readFile, writeFile, appendFile } from 'node:fs/promises';

You may also see import fs from 'node:fs' followed by fs.promises.readFile(...); both give the same functions. In this track we use node:fs/promises for the async API and node:fs only for the callback and synchronous forms (compared in the next lesson).

Writing and reading a text file

writeFile(path, data) creates the file, or replaces it completely if it exists. readFile(path) returns the content. Without an encoding it returns a Buffer (see Buffers); with 'utf8' it returns a string.

Node.js writeFile and readFile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Points to remember:

  • Paths are relative to the current working directory of the process (process.cwd()), not to the file containing the code. To find files next to your module, build the path from import.meta.dirname (Node 20.11+) or from new URL('./data.txt', import.meta.url); both are explained in ES Modules and The os and path Modules.
  • writeFile accepts strings, Buffers, typed arrays, and even async iterables. A string is encoded as UTF-8 unless you pass another encoding.
  • readFile loads the entire file into memory. That is perfect for configuration and small data files and a bad idea for a multi-gigabyte log. For big files use streams (File Streams).
  • Unlike readFile, writing never adds a newline for you. If you want your text file to end with \n, add it.

Encodings

When you give readFile an encoding, Node.js decodes the bytes for you. 'utf8' is what you want for almost all text today. Others exist ('latin1', 'utf16le', 'base64', 'hex'), but do not use 'ascii' for new code.

Node.js Encodings and binary data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The same bytes decode to nonsense in the wrong encoding, and no error is raised: files do not record their own encoding, so you and the writer have to agree. UTF-8 is the safe default for new files. If a text file begins with the three bytes EF BB BF (a "byte order mark") strip it before parsing JSON or CSV, because JSON.parse fails on it.

appendFile and flags

appendFile(path, data) adds to the end of a file and creates it if needed. It is the simplest way to write a log. It is a shortcut for writeFile with the flag 'a'.

A flag tells the operating system how to open the file. The most useful ones:

Flag Meaning
'r' Read only. The file must exist. (Default for reading.)
'w' Write. Create if missing, truncate (empty) if present. (Default for writeFile.)
'wx' Like w, but fail with EEXIST if the file already exists.
'a' Append. Create if missing.
'ax' Append, but fail if the file exists.
'r+' Read and write; the file must exist; no truncation.

The x in 'wx' stands for "exclusive". It is the correct way to say "create this file only if nobody else did", because the check and the creation happen in a single atomic step inside the operating system.

Node.js appendFile and the wx flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each appendFile call opens the file, writes, and closes it again. That is fine for occasional writes but wasteful in a hot loop; a write stream (File Streams) or a FileHandle keeps the file open.

Handling errors

File operations fail for ordinary reasons: the file does not exist, a folder is missing, you lack permission, the disk is full. The promise rejects with a system error, an Error that carries extra properties. Branch on error.code, not on the message text, which differs between operating systems.

Code Meaning Typical cause
ENOENT No such file or directory Wrong path, or the parent folder is missing
EEXIST File already exists Exclusive creation (wx, mkdir) of an existing path
EACCES, EPERM Permission denied / not permitted Insufficient rights
EISDIR Is a directory Tried to read or write a folder as a file
ENOTDIR Not a directory A path component is a file
ENOSPC No space left on device Disk full
EMFILE Too many open files A leak of open files or handles
Node.js Reading the properties of a system error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last pattern is the important one: catch only the code you expect, and re-throw the rest. Swallowing every error hides permission problems and full disks behind a silent default.

Unhandled, the same failure ends your program with a stack trace. This is what a forgotten try/catch looks like:

Node.js An uncaught ENOENT (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The run ends with Error: ENOENT: no such file or directory, open 'config.json', a stack trace whose last line points at main.mjs:3:16 (the await on line 3), and exit code 1. In a real program you would catch it near the place where you can do something useful: use a default, create the file, or print a friendly message and exit.

FileHandle: keeping a file open

readFile and writeFile open and close the file for you. When you need several operations on the same file, open gives you a FileHandle: you keep one file descriptor, read or write at specific positions, and close it yourself.

Node.js Using a FileHandle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first file.readFile call prints "", an empty string. A handle remembers a current position, and the three write calls moved it to the end of the file, so there is nothing left to read. Passing an explicit position to read (here 0) ignores the current position and returns the whole content, now starting with One because of the in-place replacement. Position-less reads and writes on one handle share that single position, which is a common source of surprises.

Two rules about handles:

  • Always close them, normally in a finally block. An unclosed handle leaks a file descriptor and eventually causes EMFILE. Node.js prints a warning and closes it on garbage collection, but you cannot rely on timing.
  • Modern Node.js handles are disposable: with await using file = await open(...) the file closes automatically at the end of the block (this works in Node.js 24, as you can try in our editor). See Modern JavaScript You Need for the using declarations.

Atomic writes: never leave half a file

writeFile first empties the file and then writes the new content. If your program crashes, the power fails or another process reads in between, the file is empty or only partly written. For a log that is acceptable; for a configuration file or database it is a disaster.

The standard fix is the write-then-rename pattern:

  1. Write the new content to a temporary file in the same directory (rename is atomic only within one file system).
  2. Flush it to disk.
  3. rename the temporary file over the target. A rename replaces the destination in one indivisible step: readers see either the complete old file or the complete new file, never a mixture.
Node.js An atomic write helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

handle.sync() forces the data out of the operating system's cache. Without it, a power cut right after rename could leave a renamed but empty file on some file systems. It makes writes slower, so use it where durability matters (configuration, state), not for caches or logs. Libraries such as write-file-atomic on npm package this pattern, including file permissions and a queue per path.

Atomic rename protects readers from half-written files. It does not protect two writers from overwriting each other's changes; if several processes update the same file you need locking or a database, such as the built-in SQLite module in SQLite with node:sqlite.

Practical advice

  • Prefer await with try/catch and expected error codes over checking first with exists; checking and then acting is a race condition (the next lesson shows why).
  • Use JSON.stringify(value, null, 2) when writing configuration files people may read, and validate on reading: a file can always be missing, empty or edited by hand.
  • Do independent reads in parallel with Promise.all. Reading three small files that way finishes when the slowest does.
  • Never build paths by concatenating user input; see Paths, Permissions and Safe File Handling.
  • Writing many small pieces to one file is faster with a single open handle or a stream than with repeated appendFile calls.
Node.js Reading several files in parallel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does await readFile('data.bin') return when you pass no encoding?

    Without an encoding Node.js gives you the raw bytes as a Buffer. Pass 'utf8' to get a string.
  2. 2. Which flag makes writeFile fail with EEXIST if the file is already there?

    The x means exclusive creation. 'w' truncates an existing file and 'a' appends to it.
  3. 3. How should you decide what to do after a failed file operation?

    Messages differ between systems; codes are stable. Re-throwing unexpected codes avoids hiding real problems such as EACCES or ENOSPC.
  4. 4. Why does the atomic-write pattern create the temporary file in the same directory as the target?

    Renaming across file systems is a copy plus delete, which is not atomic. In the same directory the replacement is a single operation.
  5. 5. What is the main risk of readFile on a very large file?

    readFile builds one buffer or string for the whole file. For big files use streams and process the data in chunks.

Summary

  • node:fs/promises gives promise-based readFile, writeFile, appendFile, open and more; relative paths resolve against process.cwd().
  • No encoding means a Buffer; use 'utf8' for text. The wrong encoding produces garbage without any error.
  • writeFile replaces, appendFile adds; flags such as 'wx' and 'a' control creation and truncation.
  • Errors are system errors with code (ENOENT, EEXIST, EACCES, EISDIR, EMFILE); handle the ones you expect and re-throw the rest.
  • A FileHandle keeps a file open for positioned reads and writes; always close it in finally.
  • Write important files atomically: temporary file, sync, then rename.
  • In the editor sandbox files live only for one run.

Next: Sync, Callback and Promise APIs