fs.writeFile()

Asynchronously writes data to a file, replacing the file if it already exists.

Since Node 10 (fs/promises) Spec ↗

Syntax

await writeFile(file, data[, options])

Parameters

NameTypeRequiredDescription
file string | Buffer | URL | integer Yes The filename or file descriptor to write to.
data string | Buffer | TypedArray | DataView Yes The data to write to the file.
options object | string No An encoding string or an object with `encoding`, `mode`, `flag`, and `signal`. Use `flag: 'a'` to append instead of overwrite.

Returns

Promise<void> — Resolves once the data is flushed.

Examples

import { writeFile } from 'node:fs/promises';

await writeFile('./out.txt', 'hello world\n', 'utf8');
console.log('written');
Output
written
import { writeFile } from 'node:fs/promises';

const data = JSON.stringify({ ok: true }, null, 2);
await writeFile('./state.json', data);

Notes

Truncates and replaces existing files by default. Concurrent `writeFile` calls to the same path are not safe and may interleave. For atomic updates write to a temp file then `rename` it.

See also