Reads a file with an optional size limit using a single file descriptor to avoid TOCTOU race conditions.
// Source: https://github.com/mperkins0155/agentsys | License: MIT | Copyright 2026 Avi Fenesh
// Provided via justclaw.it.com; keep this notice with the code.
'use strict';
const fs = require('fs');
/**
* Read a file with an optional size cap, free of check-then-use (TOCTOU)
* races.
*
* The path is opened once and every subsequent operation (the regular-file
* check, the size check, the read) acts on that file descriptor. Because the
* descriptor is bound to a single inode, swapping the path for another file or
* a symlink between calls cannot redirect the read - which a separate
* `fs.statSync(path)` / `fs.existsSync(path)` followed by `fs.readFileSync(path)`
* cannot guarantee.
*
* @param {string} filePath
* @param {number} [maxSize] - byte ceiling; larger files throw `EF
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search 40K more like it.
Get a free API key