Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Node.js · Function

writeFile

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.

Since
v0.1.29

How it works

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.

Syntax

fs.writeFile(file, data[, options], callback)
fsPromises.writeFile(file, data[, options])

Parameters

NameTypeDescription
filestring | Buffer | URL | number | FileHandlePath, file descriptor, or file handle identifying the target file.
datastring | Buffer | Uint8Array | AsyncIterable | IterableContent to write.
optionsObject | stringOptional encoding, mode, and file-opening flag settings.
callbackfunctionCallback receiving an error, or omitted for the promise API.

Returns

The callback API invokes its callback after completion; the promise API resolves when writing finishes and rejects if an error occurs.

Key points

  • Writes asynchronously and replaces existing contents by default.
  • The data input supports strings, Buffers, async iterables, and iterables.
  • The file argument can identify a path, file descriptor, or file handle.
  • The mode controls permissions when a new file is created, not an existing file.

Common mistakes

  • Do not start concurrent writes to the same file without awaiting each operation; overlapping writes are unsafe.
  • Setting an encoding has no effect when the input data is a Buffer.

Example: Write a text file asynchronously

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.

When to use it

Save application output

Persist generated text or serialized data to a file.

Append logs or events

Use an append flag to add records to an existing file.

Persist binary data

Write binary content supplied as a Buffer or typed array.

  • fs.writeFileSync
  • fsPromises.writeFile
  • filehandle.writeFile
  • fs.createWriteStream

Source: File System. Checked 2026-10-15.