Save application output
Persist generated text or serialized data to a file.
Node.js · Function
Asynchronously writes data to a file, replacing existing contents by default. It accepts strings, Buffers, and iterable data, with options for encoding, permissions, and opening behavior.
The promise-based writeFile function asynchronously writes supplied data to a path or file handle. By default it uses UTF-8 for string data and replaces an existing file; options can select an encoding, mode, or flag, and the promise resolves after the write completes.
fs.writeFile(file, data[, options], callback)
fsPromises.writeFile(file, data[, options])| Name | Type | Description |
|---|---|---|
file | string | Buffer | URL | number | FileHandle | Path, file descriptor, or file handle identifying the target file. |
data | string | Buffer | Uint8Array | AsyncIterable | Iterable | Content to write. |
options | Object | string | Optional encoding, mode, and file-opening flag settings. |
callback | function | Callback receiving an error, or omitted for the promise API. |
The callback API invokes its callback after completion; the promise API resolves when writing finishes and rejects if an error occurs.
import { writeFile } from 'node:fs/promises';
await writeFile('message.txt', 'Hello, Node.js!');
console.log('File saved');Writes UTF-8 text asynchronously and replaces the file if it already exists.
Persist generated text or serialized data to a file.
Use an append flag to add records to an existing file.
Write binary content supplied as a Buffer or typed array.
fs.writeFileSyncfsPromises.writeFilefilehandle.writeFilefs.createWriteStream