File system

fs/promises.writeFile()

Writes data to a file, normally creating or replacing it. Tested on Node.js 22.16.0. The wx flag prevents accidental replacement; do not overlap writes to the same file without coordination.

Formal Syntax & Structure

nodejs syntaxnodejs
fsPromises.writeFile(file, data[, options])

Parameters & Attributes

NameTypeDescription
filestring | Buffer | URL | FileHandleDestination.
datastring | Buffer | TypedArray | DataView | Iterable | AsyncIterable | StreamContent.
optionsstring | objectEncoding, flag, mode, flush or signal as applicable.

Return Value

Promise<void>

Resolves when write finishes.

Working Example

Example Snippetnodejs
import * as fs from 'node:fs/promises';import { join } from 'node:path';import { tmpdir } from 'node:os';const dir=await fs.mkdtemp(join(tmpdir(),'bytemind-ref-'));try {  const file=join(dir,'note.txt');  await fs.writeFile(file,'draft',{flag:'wx'});  console.log(await fs.readFile(file,'utf8'));} finally { await fs.rm(dir,{recursive:true,force:true}); }
Node.js Reference