Filesystem

fs/promises.truncate()

Changes file length in bytes, discarding data beyond the new length. Do not truncate files you do not own. Tested on Node.js 22.16.0. Example output (one line per entry): ["cat"].

Formal Syntax & Structure

nodejs syntaxnodejs
truncate(path[, len])

Parameters & Attributes

NameTypeDescription
pathstring | URLOwned file path.
lennumberNew byte length.

Return Value

Promise<void>

Completes after resizing.

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');    await fs.truncate(p, 3);    console.log(await fs.readFile(p, 'utf8'));}finally {    await fs.rm(dir, { recursive: true, force: true });}
Node.js Reference