How to Read and Write Files in Node.js With the fs Module

Quick Summary

  • Node.js reads files with fs.readFile() and creates or overwrites them with fs.writeFile(), from the built-in fs module; pass 'utf-8' to get a string instead of a Buffer.
  • Each method has a blocking Sync version, a callback version, and a promise version in node:fs/promises that you use with await.
  • Asynchronous calls finish later, so read a file after its write has completed, check for errors such as ENOENT, and build paths from __dirname or import.meta.dirname.

Node.js reads and writes files with its built-in fs (file system) module, so there’s nothing to install. Use fs.readFile() to read a file and fs.writeFile() to create or overwrite one. Each comes in three styles: synchronous (readFileSync(), which blocks until it’s done), callback (readFile() with a function that runs when it’s done) and promise (readFile() from node:fs/promises, used with await).

The syntax

Code
// Callback API: require('node:fs')
fs.readFile(path[, options], callback)
fs.writeFile(file, data[, options], callback)
fs.appendFile(path, data[, options], callback)

// Synchronous API: require('node:fs')
fs.readFileSync(path[, options])
fs.writeFileSync(file, data[, options])

// Promise API: require('node:fs/promises')
fsPromises.readFile(path[, options])
fsPromises.writeFile(file, data[, options])
fsPromises.appendFile(path, data[, options])

These are the signatures as the Node.js fs documentation writes them; the square brackets mark optional arguments, so this block is a reference, not code to run. options is usually just the encoding, such as 'utf-8'. Without an encoding, a read gives you a Buffer instead of a string. writeFile() replaces the file’s content if the file exists and creates it if it doesn’t; appendFile() adds to the end instead.

A full example: sync and callbacks

Save the code as a .js file and run it with node. It expects a txt folder containing input.txt and start.txt in the directory you run it from.

JavaScript
// fs stands for File System
const fs = require('node:fs');

// BLOCKING, SYNCHRONOUS WAY
const textIn = fs.readFileSync('./txt/input.txt', 'utf-8');

const textOut = `This is NMH47 Talking About Avocado: ${textIn}.\nCreated on ${Date.now()}`;
fs.writeFileSync('./txt/amar-output.txt', textOut);

const textShow = fs.readFileSync('./txt/amar-output.txt', 'utf-8');
console.log(textShow);

// NON-BLOCKING, ASYNCHRONOUS WAY (callbacks)
fs.readFile('./txt/start.txt', 'utf-8', (err, data) => {
    if (err) {
        return console.error(err.message);
    }
    console.log(data);
});

const data2 = 'Sherlock';
const data3 = 'Holmes';

fs.writeFile('./txt/nexus.txt', `${data2} ${data3}`, 'utf-8', err => {
    if (err) {
        return console.error(err.message);
    }
    console.log('File has been written successfully');

    // Read the file only after writeFile() has finished.
    fs.readFile('./txt/nexus.txt', 'utf-8', (err, data) => {
        if (err) {
            return console.error(err.message);
        }
        console.log(data);
    });
});

With input.txt containing Avocados are green and start.txt containing Read this first, Node.js 24 printed:

Code
This is NMH47 Talking About Avocado: Avocados are green.
Created on 1790548378671
Read this first
File has been written successfully
Sherlock Holmes

Blocking, synchronous way

  • fs.readFileSync() reads input.txt and returns its content as a string, because of the 'utf-8' encoding.
  • A template literal builds new text from that content and Date.now(), the current time in milliseconds.
  • fs.writeFileSync() saves the text to amar-output.txt, creating the file or replacing its content. The file is then read back and logged.

Each call finishes before the next line runs. That’s simple and fine for scripts and build tools, but it blocks Node’s event loop, so a server couldn’t handle other requests in the meantime.

Non-blocking, asynchronous way

fs.readFile() and fs.writeFile() start the work and call your callback when it’s done, with an error (err) as the first argument. Node keeps running the rest of the code meanwhile.

  • Because of that, a readFile() of nexus.txt placed after writeFile() could run before the write has finished. Calling it inside the writeFile() callback, as above, makes sure it reads the new text.
  • Each callback checks err first. When a file is missing, err.code is 'ENOENT' and data is undefined.

The same with promises and async/await

Nested callbacks get hard to read quickly. The promise version of the module, node:fs/promises, lets you write the same steps top to bottom with await, and handle errors in one place:

JavaScript
const fs = require('node:fs/promises');

async function main() {
    const start = await fs.readFile('./txt/start.txt', 'utf-8');
    console.log(start);

    await fs.writeFile('./txt/nexus.txt', 'Sherlock Holmes', 'utf-8');
    await fs.appendFile('./txt/nexus.txt', '\n221B Baker Street', 'utf-8');

    const nexus = await fs.readFile('./txt/nexus.txt', 'utf-8');
    console.log(nexus);
}

main().catch(err => {
    console.error(err.message);
    process.exitCode = 1;
});

This printed Read this first, then Sherlock Holmes and 221B Baker Street on two lines. Each await waits for its step, so the file is always read after it has been written, and any error, such as a missing file, ends up in catch().

In an ES module (a .mjs file, or "type": "module" in package.json) you import the functions and can use await at the top level:

JavaScript
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';

const dir = join(import.meta.dirname, 'txt');

await mkdir(dir, { recursive: true });
await writeFile(join(dir, 'notes.txt'), 'Written next to the script', 'utf-8');
console.log(await readFile(join(dir, 'notes.txt'), 'utf-8'));

mkdir() with recursive: true creates the folder if it doesn’t exist and does nothing if it does, so writeFile() doesn’t fail on a missing folder. import.meta.dirname is the folder of the script itself; it was added in Node.js 20.11 and 21.2. In a CommonJS file, use __dirname instead.

Which one should you use?

  • Promises with async/await for most new code: readable, and it doesn’t block the event loop.
  • Callbacks when you work in older code that already uses them. The Node.js docs note that the callback API is the better choice when you need maximum performance.
  • Sync methods in short scripts, CLI tools and at startup, before a server begins handling requests.

Things to check

  • Relative paths like ./txt/input.txt are resolved from the folder you run node in, not from the script’s location. Running the promise example from its parent folder failed with ENOENT: no such file or directory. Build paths from __dirname or import.meta.dirname to avoid that.
  • readFile() loads the whole file into memory. That’s fine for text and config files; for very large files, read them in pieces with fs.createReadStream().
  • The node: prefix (require('node:fs')) makes clear that you mean the built-in module. require('fs') loads the same module.
Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More