Asynchronous file operations and API selection with fs/promises

Sequence file operations with await and handle asynchronous read failures.

🎯 Introduction

By the end of this article, you will be able to sequence file operations with await and handle asynchronous read failures.


🧱 Choose a file API: use asynchronous operations for everyday tasks

node:fs/promises provides file operations that return Promises, allowing you to organize reads and writes with the await syntax you know. While waiting for a file operation, Node.js can process other ready tasks. Synchronous methods such as readFileSync instead keep the current JavaScript waiting.

API sourceHow results are deliveredSuggested use
readFile from node:fs/promisesThe Promise fulfills with the file contentsEveryday asynchronous file operations
readFileSync from node:fsReturns the file contents directlyShort scripts or small startup configuration files
readFile from node:fsPasses errors or contents to a callbackMaintaining existing callback-based code

All these methods read the entire file. Asynchronous methods do not automatically reduce the memory occupied by its contents. Use streams, covered later, to read large files in chunks.


🛠 Finish writing before reading the new content

When operations depend on earlier results, wait for each preceding step to finish. Save this separately as write-read.mjs:

import { writeFile, readFile } from 'node:fs/promises'
await writeFile('promise-note.txt', 'new content', 'utf8')
const text = await readFile('promise-note.txt', 'utf8')
console.log(text)

This prints new content. The writeFile Promise fulfills with undefined: you are waiting for the write to finish, not retrieving contents. The next line reads the string.

Removing await before the write may allow the read to happen before writing finishes, making the result unreliable. The order of two lines in a file does not determine when their asynchronous operations finish.


🪤 Handle failed file operations

Catch read failures within the current task and report that the task failed. Save this as read-required.mjs and test with a missing missing.txt:

read-required.mjs
import { readFile } from 'node:fs/promises'

try {
    const text = await readFile('missing.txt', 'utf8')
    console.log(text)
} catch (error) {
    if (error.code === 'ENOENT') {
        console.error('Required file missing.txt is missing; check the path')
    } else {
        console.error('Read failed:', error.code)
    }
    process.exitCode = 1
}

This prints Required file missing.txt is missing; check the path and exits with code 1. process.exitCode reports failure to the terminal that started the script; see the process article for details. Print contents only after a successful read. Do not continue processing nonexistent data after failure.

Use error.code to distinguish causes: ENOENT means a path is missing; EACCES means insufficient permissions. Check codes rather than error messages that may vary between environments, and do not report every failure as “file not found.”


⚖️ When reads can run concurrently

Reads of two independent small files can start together so that their waiting time overlaps. First check whether either task needs the other's result. Writing and then reading the same file does not meet this condition.

For example, prepare two independent configuration files in the same directory: app.txt containing app and user.txt containing user. Run this separately as read-two.mjs:

read-two.mjs
import { readFile } from 'node:fs/promises'
const [app, user] = await Promise.all([
    readFile('app.txt', 'utf8'),
    readFile('user.txt', 'utf8')
])
console.log(app, user)

This prints app user. Both reads start together, but results retain input order regardless of which finishes first. If either fails, this await throws. To report failure, wrap the task in try/catch as in the previous section.

However, await consecutive writes to the same file in order. Do not start an unlimited number of file tasks at once; this increases pressure on memory and file resources. Get dependencies right first, then limit concurrency according to actual needs.


❓ Questions and answers

Q1: Does asynchronous readFile return chunks?

No. It still returns the entire file after reading it. Use a stream for chunked processing.

Q2: Does placing a synchronous method in an async function make it nonblocking?

No. The synchronous method still blocks the current JavaScript while it executes.

Q3: Can consecutive writes to one file start together?

Wait for each write before starting the next. Otherwise, completion order and file contents may not match your expectations.


🧪 Exercise

Add appendFile between the write and read, append a line of text, and await its completion. Verify that the read includes both the original and appended content. See the previous article for appendFile arguments.

// Write your code here

🎉 Try these techniques with your own examples!