---
title: "How do I read and write files in Node.js with fs/promises?"
description: "The fs/promises module gives you async file functions you can await. Learn how to read, write, append and list files, handle missing files, and stream large ones."
url: https://www.danny.engineering/answer/nodejs/how-do-i-read-and-write-files-in-nodejs-with-fspromises
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T17:24:00.000Z
tags: ["Node.js"]
---

# How do I read and write files in Node.js with fs/promises?

## The short answer


Import the functions from `node:fs/promises` and `await` them. Pass an encoding such as `'utf8'` when you want a string back instead of a Buffer.


```javascript
import { readFile, writeFile } from 'node:fs/promises';

const text = await readFile('notes.txt', 'utf8');
await writeFile('notes-copy.txt', text);
```


## Why it happens


Node's `fs` module has three styles of the same functions:

- **Callback**, such as `fs.readFile(path, callback)`, the original API.
- **Sync**, such as `fs.readFileSync(path)`, which blocks the whole process until the disk responds.
- **Promise**, from `node:fs/promises`, which returns promises you can `await`.

The promise API is the one to reach for in modern code. It works with `async` and `await`, it does not block other requests while the disk is busy, and errors become normal exceptions you can catch with `try` and `catch`. The sync versions are still fine for short scripts and start-up code, where blocking does not matter.


One thing catches people out: relative paths are resolved from the current working directory, which is wherever the process was started, not from the file that contains the code.


## How to fix it


### Build paths from the current file


Use `import.meta.dirname` in ES modules, or `__dirname` in CommonJS, so the path works no matter where you run the script from.


```javascript
import { readFile } from 'node:fs/promises';
import path from 'node:path';

const configPath = path.join(import.meta.dirname, 'config.json');
const config = JSON.parse(await readFile(configPath, 'utf8'));
```


### Write, append and create folders


`writeFile` replaces the file, creating it if needed. `appendFile` adds to the end. Neither creates missing folders, so call `mkdir` with `recursive: true` first.


```javascript
import { mkdir, writeFile, appendFile } from 'node:fs/promises';

await mkdir('output/reports', { recursive: true });

await writeFile(
  'output/reports/summary.json',
  JSON.stringify({ total: 42 }, null, 2),
);

await appendFile('output/log.txt', `Finished at ${new Date().toISOString()}\n`);
```


### Handle missing files


If the file does not exist, the promise rejects with an error whose `code` is `'ENOENT'`. Check for it rather than testing for the file first, which can race with other processes.


```javascript
import { readFile } from 'node:fs/promises';

async function readJson(file, fallback) {
  try {
    return JSON.parse(await readFile(file, 'utf8'));
  } catch (error) {
    if (error.code === 'ENOENT') return fallback;
    throw error;
  }
}

const settings = await readJson('settings.json', {});
```


### List, inspect and delete


```javascript
import { readdir, stat, rm } from 'node:fs/promises';

const entries = await readdir('output', { withFileTypes: true });

for (const entry of entries) {
  if (entry.isFile()) {
    const info = await stat(`output/${entry.name}`);
    console.log(entry.name, info.size);
  }
}

await rm('output/tmp', { recursive: true, force: true });
```


### Stream large files


`readFile` loads the whole file into memory. For large logs or CSV files, read it line by line with a stream instead.


```javascript
import { open } from 'node:fs/promises';

const file = await open('big.log');

for await (const line of file.readLines()) {
  if (line.includes('ERROR')) console.log(line);
}
```


### Write safely


If the process crashes halfway through `writeFile`, you can be left with a half-written file. For important data, write to a temporary file and rename it, which replaces the original in one step on the same drive.


```javascript
import { writeFile, rename } from 'node:fs/promises';

await writeFile('data.json.tmp', JSON.stringify(data));
await rename('data.json.tmp', 'data.json');
```


## Common pitfalls

- Forgetting `'utf8'` and getting a Buffer, which prints as a list of bytes.
- Forgetting `await`, so the code carries on before the file is written.
- Running many writes to the same file in parallel with `Promise.all`. The order is not guaranteed; write in sequence or collect the data first.
- Using `existsSync` before reading. Just read and handle `ENOENT`.
- Reading huge files with `readFile` and running out of memory. Stream them.

## Related reading

- [Node.js: File system, promises API](https://nodejs.org/api/fs.html#promises-api)
- [Node.js: Path](https://nodejs.org/api/path.html)
