truncate

import { truncate } from "jsr:@ende/fs/unstable-truncate";

function · experimental · requires --allow-write

async function truncate(name: string, len?: number): Promise<void>

Truncates (or extends) the specified file, to reach the specified len. If len is not specified then the entire file contents are truncated.

Requires allow-write permission.

name: string

The name/path to the file.

len?: number

An optional value that sets the new size of the file. Omitting this argument sets the file size to 0 bytes.

Example: Truncate file to 0 bytes

import { truncate } from "@ende/fs/unstable-truncate";
await truncate("my_file.txt");

Example: Truncate part of a file

import { makeTempFile } from "@ende/fs/unstable-make-temp-file";
import { readFile } from "@ende/fs/unstable-read-file";
import { truncate } from "@ende/fs/unstable-truncate";
import { writeTextFile } from "@ende/fs/unstable-write-text-file";
import { assertEquals } from "@ende/assert";

const file = await makeTempFile();
await writeTextFile(file, "Hello World");
await truncate(file, 7);
const data = await readFile(file);
assertEquals(new TextDecoder().decode(data), "Hello W");

Source