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

Node.js · Function

createWriteStream

Creates and returns a writable stream connected to a file. Use it to write data incrementally while controlling file-opening behavior through options.

Since
v0.1.31

How it works

createWriteStream opens a file-backed writable stream. Data can be supplied incrementally with stream methods such as write() and end(); options control how the file is opened, encoded, positioned, and permissioned.

Syntax

fs.createWriteStream(path[, options])

Parameters

NameTypeDescription
pathstring | Buffer | URL | integerFile path to open, or a path-like value accepted by the Node.js file-system API.
optionsobject | stringOptional stream and file-opening settings, including flags, encoding, fd, mode, and start.

Returns

A new WriteStream object.

Key points

  • The function returns a writable file stream that follows Node.js Writable Stream behavior.
  • Use start to begin writing at an offset instead of position zero.
  • The default opening mode is w, while r+ is relevant for in-place modification.
  • The stream's default encoding can be selected from encodings supported by Buffer.
  • A supplied descriptor should be blocking; non-blocking descriptors are not appropriate for this API.

Common mistakes

  • The default w flag replaces or creates the file; choose r+ when modifying an existing file without truncating it.
  • When supplying fd, the path is ignored and the stream uses that descriptor instead.
  • A caller-provided file descriptor does not cause the stream to emit open.

Example: Write text incrementally to a file

import { createWriteStream } from 'node:fs';

const output = createWriteStream('output.txt');
output.write('First line\n');
output.end('Last line\n');
output.on('finish', () => console.log('File written'));

Creates a writable file stream, writes two chunks, and reports completion after the stream finishes.

When to use it

Incremental file output

Write logs or generated content progressively without constructing the entire file in memory.

Streaming generated data

Produce a file while another operation generates chunks over time.

Offset or in-place writes

Write to a chosen file offset or modify an existing file with suitable flags.

  • WriteStream
  • Writable Stream
  • fs.createReadStream
  • fs.write

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