Filesystem

FileHandle.write()

Writes a region of a buffer. Check bytesWritten and complete partial writes when building a general write loop. Tested on Node.js 22.16.0. Example output (one line per entry): ["1", "cXtalog"].

Formal Syntax & Structure

nodejs syntaxnodejs
handle.write(buffer, offset, length, position)

Parameters & Attributes

NameTypeDescription
bufferBufferBytes to write.
offsetnumberOffset in buffer.
lengthnumberRequested byte count.
positionnumber | nullFile offset or current position.

Return Value

Promise<object>

Bytes written and buffer.

Working Example

Example Snippetnodejs
import * as fs from 'node:fs/promises';import { constants } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';const dir = await fs.mkdtemp(join(tmpdir(), 'bytemind-'));try {    const p = join(dir, 'book.txt');    await fs.writeFile(p, 'catalog');    const h = await fs.open(p, 'r+');    try {        const b = Buffer.from('X');        console.log((await h.write(b, 0, 1, 1)).bytesWritten);    }    finally {        await h.close();    }    console.log(await fs.readFile(p, 'utf8'));}finally {    await fs.rm(dir, { recursive: true, force: true });}
Node.js Reference