# Save some text to a file in Node.js

> Learn how to save text to a file in Node.js using the fs module and the writeFile method, with a simple example that handles errors and confirms when done.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2023-05-12 | Updated: 2026-08-07 | Topics: [Node.js](https://flaviocopes.com/tags/node/) | Canonical: https://flaviocopes.com/save-some-text-to-a-file-in-nodejs/

So you want to save some text to a file using [Node.js](https://flaviocopes.com/nodejs/).

The `fs.writeFile()` method does it. Pass the file path, the text, and a callback that runs when writing completes:

```javascript
import fs from 'node:fs'

const text = 'yo'

fs.writeFile('text.txt', text, (err) => {
  if (err) {
    console.error(err)
    return
  }
  console.log('done')
})
```

This creates `text.txt` in the current working directory. If the file already exists, its content is **replaced**. Keep that in mind: `writeFile()` overwrites, it does not append.

The text is written as UTF-8 by default, which is what you want almost every time.

One more thing: `writeFile()` wants a string (or a buffer). To save an object, convert it first with `JSON.stringify()`, or you'll get a `TypeError`.

## The promises version

I prefer the promise-based API from `node:fs/promises`, since it works with `await`:

```javascript
import fs from 'node:fs/promises'

await fs.writeFile('notes.txt', 'Meeting at 10am')
```

Top-level `await` works in ES modules, so this is all you need. Wrap it in a `try/catch` if you want to handle write errors.

## The sync version

There's also `fs.writeFileSync()`, which blocks until the file is written:

```javascript
import fs from 'node:fs'

fs.writeFileSync('notes.txt', 'Meeting at 10am')
```

Fine for small scripts and CLI tools. Avoid it in a server, where blocking the event loop means blocking every request.

## How to append instead of overwrite

Use `fs.appendFile()`:

```javascript
import fs from 'node:fs/promises'

await fs.appendFile('app.log', 'user logged in\n')
```

Each call adds to the end of the file, creating it if it doesn't exist yet. Handy for logs.

You can get the same behavior from `writeFile()` by passing the `a` flag:

```javascript
await fs.writeFile('app.log', 'user logged in\n', { flag: 'a' })
```

## A common error: the folder doesn't exist

`writeFile()` creates the file, but not the folders in the path. Writing to `data/notes.txt` when there's no `data` folder fails with `ENOENT: no such file or directory`.

The fix is to create the folder first:

```javascript
import fs from 'node:fs/promises'

await fs.mkdir('data', { recursive: true })
await fs.writeFile('data/notes.txt', 'Meeting at 10am')
```

With `recursive: true`, `mkdir()` creates any missing parent folders, and it doesn't complain if the folder is already there.
