Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท fs and fs/promises

Node.js fs.createWriteStream() method

Reference for fs.createWriteStream() in Node.js: write large or incremental output to a file, append with flags, handle backpressure and wait for finish.

fs.createWriteStream(path[, options]) returns a fs.WriteStream, a writable stream that writes everything you give it to a file. Use it when output is produced piece by piece (logs, exports, downloads) or is too big to hold in memory as one string.

By default the file is created or truncated when the stream opens. Pass flags: 'a' to append instead. Data is written in the order you call write(); the file is complete only after the 'finish' event (or 'close'), which is what you should wait for.

NODE
import { createWriteStream } from 'node:fs';

const out = createWriteStream('export.csv');
out.write('id,name\n');
out.end('1,Ada\n');

Try it

Node.js Writing lines and waiting for finish

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Appending and honouring backpressure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
fs.createWriteStream(path[, options]): fs.WriteStream

// options: string (encoding) | {
//   flags?: string,            // default 'w'
//   encoding?: string,         // default 'utf8'
//   fd?: number | FileHandle,
//   mode?: number,             // default 0o666
//   autoClose?: boolean,       // default true
//   emitClose?: boolean,       // default true
//   start?: number,            // position to start writing at
//   highWaterMark?: number,    // default 16384
//   flush?: boolean,           // default false
//   signal?: AbortSignal,
//   fs?: object
// }
Option Description
flags Open flag. 'w' truncates, 'a' appends, 'wx' fails if the file exists, 'r+' modifies without truncating (use with start).
encoding How string chunks are converted to bytes.
start Byte position where writing begins. Changing a file in the middle needs flags: 'r+'.
highWaterMark Buffer size in bytes at which write() starts returning false.
flush When true, the data is flushed to the storage device before the file is closed.
fd, autoClose Write to a descriptor you opened; with autoClose it is closed on finish or error.

Returns: a fs.WriteStream with path, bytesWritten and pending, the events 'open', 'ready', 'close', and all the usual writable events and methods (write, end, cork, destroy).

Errors: reported with the 'error' event, for example ENOENT (missing directory), EACCES, EISDIR, EEXIST (flag wx).

Usage notes

  • end() is not "done". The data is on disk (as far as the OS is concerned) only after 'finish' or 'close'. Await stream.finished() from node:stream/promises or use pipeline().
  • Backpressure: write() returns false when the buffer is above highWaterMark. Stop and wait for 'drain', as the second example does. Ignoring it makes memory grow with a slow disk.
  • Always listen for 'error'. An unhandled one terminates the process. The file is opened asynchronously, so even a bad path surfaces as an event rather than an exception.
  • Truncates by default. Opening an existing file with 'w' empties it immediately, before any data is written.
  • Several writers, one file: two streams on the same path interleave unpredictably. Use one stream, or flags: 'a' for log-style appends of whole lines.
  • Order is preserved, but each write() is asynchronous. Do not mix with fs.writeSync() on the same path.
  • Durability: flush: true or a later fsync() guards against power loss; otherwise data can sit in the OS cache.
  • Piping: readable.pipe(out) or pipeline(readable, out) copies with proper backpressure; see createReadStream().