denoland/deno · error · Error

'truncate' option requires 'write' to be true

Error message

'truncate' option requires 'write' to be true

What it means

Part of checkOpenOptions for Deno.open/openSync: truncation modifies file contents, which requires the file to be opened for writing. Specifying truncate: true without write: true (including the combination with append) throws a plain Error before the file is touched.

Source

Thrown at ext/fs/30_fs.js:807

  [SymbolDispose]() {
    core.tryClose(this.#rid);
  }
}

function checkOpenOptions(options) {
  if (
    ArrayPrototypeFilter(
      ObjectValues(options),
      (val) => val === true,
    ).length === 0
  ) {
    throw new Error(
      "'options' requires at least one option to be true",
    );
  }

  if (options.truncate && !options.write) {
    throw new Error(
      "'truncate' option requires 'write' to be true",
    );
  }

  const createOrCreateNewWithoutWriteOrAppend =
    (options.create || options.createNew) &&
    !(options.write || options.append);

  if (createOrCreateNewWithoutWriteOrAppend) {
    throw new Error(
      "'create' or 'createNew' options require 'write' or 'append' to be true",
    );
  }
}

function readFileSync(path) {
  return op_fs_read_file_sync(pathFromURL(path));
}

View on GitHub (pinned to 89f33cbef2)

Solutions

  1. Add write: true: Deno.open(path, { write: true, truncate: true })
  2. For a full Node-'w' equivalent use { write: true, create: true, truncate: true }
  3. Do not combine truncate with append; choose one write mode

Example fix

// before
await Deno.open("/tmp/log", { truncate: true }); // Error

// after
await Deno.open("/tmp/log", { write: true, truncate: true });
Defensive patterns

Strategy: validation

Validate before calling

function normalizeOpenOptions(o) {
  if (o.truncate) o = { ...o, write: true };
  return o;
}
await Deno.open(path, normalizeOpenOptions(options));

Type guard

function areTruncateOptionsValid(o: { truncate?: boolean; write?: boolean }): boolean {
  return !o.truncate || o.write === true;
}

Try / catch

try {
  file = await Deno.open(path, options);
} catch (err) {
  if (err instanceof Error && err.message === "'truncate' option requires 'write' to be true") {
    file = await Deno.open(path, { ...options, truncate: false, write: true, truncate: true });
  } else throw err;
}

Prevention

When it happens

Trigger: Deno.open(path, { truncate: true }) or Deno.openSync(path, { truncate: true, append: true }) — truncate true while write is not true.

Common situations: Porting Node's 'w' flag piecewise and forgetting write; attempting to emulate touch/clear-file semantics; combining truncate with append expecting O_TRUNC|O_APPEND behavior.

Related errors


AI-assisted analysis of denoland/deno@89f33cbef2 (2026-08-16). Data as JSON: /api/errors/cd588482f3379fa7. Report an issue: GitHub.