Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท fs and fs/promises

Node.js fs.writeFile() method

Reference for fs.writeFile() and fsPromises.writeFile() in Node.js: replace a file's contents, data types, flags, mode, flush option, atomic-write pattern and errors.

fs.writeFile() writes data to a file, creating it if it does not exist and replacing its contents if it does. It does not block the event loop; the callback runs when the data has been handed to the operating system. The promise version, fsPromises.writeFile(), resolves with undefined when done.

The whole payload is written in one go, so it suits small and medium files such as configuration, generated reports or cached JSON. To add to the end of a file instead of replacing it, use fs.appendFile(); for large or continuous output use a write stream.

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

await writeFile('out.txt', 'hello\n');

Try it

Node.js Writing strings, bytes and JSON

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 Flags, errors and a safer replace

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.writeFile(file, data, callback)
fs.writeFile(file, data, options, callback)
fsPromises.writeFile(file, data, options?): Promise<void>

// file:    string | Buffer | URL | integer (file descriptor) | FileHandle (promise form)
// data:    string | Buffer | TypedArray | DataView | (promise form) Iterable | AsyncIterable | Stream
// options: string (encoding) | { encoding?, mode?, flag?, flush?, signal? }
Name Description
file Path, URL or descriptor to write to.
data What to write. Strings are encoded with options.encoding; buffers and typed arrays are written as bytes. Numbers and plain objects are rejected.
options.encoding For string data, default 'utf8'.
options.mode Permission bits for a newly created file, default 0o666 (reduced by the process umask). Ignored when the file already exists.
options.flag Default 'w' (create or truncate). 'wx' fails if the file exists, 'a' appends, 'r+' overwrites from the start without truncating. See flags.
options.flush If true, flush data to disk before closing (like fsync). Default false.
options.signal An AbortSignal to cancel a pending write.

Returns: nothing (the callback gets (error); the promise resolves to undefined).

Errors: ENOENT when a parent folder is missing, EACCES, EISDIR, EEXIST (with 'wx'), ENOSPC, and ERR_INVALID_ARG_TYPE for unsupported data.

Usage notes

  • It replaces. An existing file is truncated first. If the process dies halfway, you can be left with a partial file.
  • Atomic replace. Write a temporary file in the same folder and rename() it over the target, as in the second example. A rename within one file system is atomic.
  • Parent folders are not created. Call fs.mkdir() with { recursive: true } first.
  • Do not overlap writes to one file. Several concurrent writeFile() calls on the same path can interleave; await each one, or queue them.
  • Success does not mean durable. The data may still sit in the operating system's cache. Use flush: true or fs.fsync() when losing the last write on a power cut matters.
  • Convert first. Use JSON.stringify() for objects and String() for numbers. Writing a number or object directly throws ERR_INVALID_ARG_TYPE.
  • Descriptors and handles. With a descriptor, writing starts at its current position and the descriptor stays open afterwards, so you must close it.
  • Newlines. Node writes exactly the characters you give it; add \n yourself.