fs.writeFileSync()

Synchronously writes data to a file, blocking the event loop.

Since Node 0.x Spec ↗

Syntax

fs.writeFileSync(file, data[, options])

Parameters

NameTypeRequiredDescription
file string | Buffer | URL | integer Yes The filename or file descriptor.
data string | Buffer | TypedArray | DataView Yes The data to write.
options object | string No Encoding string or object with `encoding`, `mode`, and `flag`.

Returns

void — Returns nothing; throws on error.

Examples

import { writeFileSync } from 'node:fs';

writeFileSync('./version.txt', '1.4.0\n');
console.log('done');
Output
done
import { writeFileSync } from 'node:fs';

process.on('exit', () => {
  writeFileSync('./state.json', JSON.stringify(state));
});

Notes

Useful in `process.on('exit')` handlers and CLI tools where async work cannot complete. Avoid in servers: it stalls all concurrent requests. Truncates existing files unless `flag: 'a'`.

See also