Save some text to a file in Node.js
By Flavio Copes
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.
So you want to save some text to a file using Node.js.
The fs.writeFile() method does it. Pass the file path, the text, and a callback that runs when writing completes:
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:
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:
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():
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:
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:
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.
Related posts about node: