Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท fs and fs/promises

Node.js fs.writeFileSync() method

Reference for fs.writeFileSync() in Node.js: write strings or binary data to a file, control flags, mode and encoding, and avoid common sync-I/O mistakes.

fs.writeFileSync(file, data[, options]) writes the whole data to a file and blocks the thread until the operating system has accepted the bytes. If the file does not exist it is created; if it exists its previous content is replaced (unless you change the flag).

Because it blocks, it is a good fit for start-up code, build scripts and small command-line tools, and a poor fit for servers that handle many requests at once. There is no return value: success means "no exception was thrown".

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

writeFileSync('notes.txt', 'hello\n');

Try it

Node.js Writing text, then appending with a flag

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 Binary data, encodings and a failing flag

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.writeFileSync(file, data[, options]): undefined

// file:    string | Buffer | URL | integer (file descriptor)
// data:    string | Buffer | TypedArray | DataView
// options: string (encoding) | {
//   encoding?: string,   // default 'utf8', only used when data is a string
//   mode?: integer,      // default 0o666, only used when the file is created
//   flag?: string,       // default 'w'
//   flush?: boolean      // default false
// }
Name Description
file Path of the file, a file: URL, or an open file descriptor (then the flag is ignored and writing starts at the current position).
data The content. Strings are encoded; buffers and typed arrays are written byte for byte.
options.encoding How a string is turned into bytes. Passing a string instead of an object is shorthand for this.
options.mode Permission bits for a newly created file, reduced by the process umask.
options.flag The open flag, see file system flags.
options.flush When true, the data is flushed to the storage device before the file is closed.

Returns: undefined.

Errors: throws synchronously. Common code values are ENOENT (a parent directory is missing), EACCES, EISDIR (the path is a directory), EEXIST (flag wx and the file exists) and ERR_INVALID_ARG_TYPE (for example when data is a number or plain object).

Usage notes

  • Replaces by default. Flag 'w' truncates an existing file first. If your process crashes halfway, the file can be left empty or partly written. For important files, write to a temporary name and then rename() it into place, which is atomic on the same file system.
  • Only strings and binary views. Objects, numbers and arrays throw ERR_INVALID_ARG_TYPE. Use JSON.stringify() or String() yourself.
  • Parent directories are not created. Call mkdirSync(dir, { recursive: true }) first.
  • mode only matters on creation. Overwriting an existing file keeps its permissions. Use chmodSync() to change them afterwards.
  • flush: true costs time but reduces the chance of losing data on a power failure. Without it, "written" means the operating system has the bytes, not that the disk has.
  • Blocking. The whole event loop waits. Inside request handlers prefer fs.promises.writeFile().
  • File descriptors: when file is a descriptor you keep control of it; the function does not close it.
  • Large data: a very large string or buffer is held in memory. For gigabytes, stream with createWriteStream().