2.9 KiB
2.9 KiB
getDataFromFile
(no submodules)
Purpose
getDataFromFile reads a file from the local filesystem and returns its contents
as a plain Uint8Array. It is a thin Node-only convenience for the streams
package: the streams package is environment-agnostic, but many byte-oriented
helpers (chunking, framing, hashing) need a way to load test fixtures and
real-world inputs from disk without each call site re-implementing the dynamic
import + error-mapping dance.
The function is browser-safe in the sense that importing it does not pull in
node:fs eagerly. The Node module is loaded lazily inside the function body and
calling it in a non-Node environment surfaces a structured
StreamFileBrowserNotSupportedError rather than an opaque module-resolution
crash.
Features
- Lazy
node:fs/promisesimport — zero overhead on the browser bundle path. - Runtime environment detection via
globalThis.process?.versions?.node. - Returns a fresh
Uint8Arraydecoupled from Node's pooledBufferallocator. - Structured errors with the original
causeand the offendingfilePath. - Stable
STREAM.FILE_BROWSER_NOT_SUPPORTEDandSTREAM.FILE_READ_FAILEDcodes.
Usage: Basic Example
import { getDataFromFile } from "@suaveplan/streams/utils/buffer/get-data-from-file/get-data-from-file";
const bytes = await getDataFromFile("/etc/hostname");
console.log(bytes.byteLength);
Usage: Advanced Example
import { getDataFromFile } from "@suaveplan/streams/utils/buffer/get-data-from-file/get-data-from-file";
import { StreamFileReadFailedError } from "@suaveplan/streams/errors/stream-error";
try {
const data = await getDataFromFile("/no/such/file");
process.stdout.write(data);
} catch (err) {
if (err instanceof StreamFileReadFailedError) {
console.error("read failed", err.context, err.cause);
} else {
throw err;
}
}
API Reference
getDataFromFile(filePath: string): Promise<Uint8Array>
filePath— absolute or relative path resolved againstprocess.cwd().- Returns —
Promise<Uint8Array>containing the file's exact bytes. - Throws —
StreamFileBrowserNotSupportedErroroutside Node;StreamFileReadFailedError(withcauseandcontext.filePath) on any underlying I/O failure (ENOENT, EACCES, EISDIR, …).
Implementation Notes
- The dynamic
import("node:fs/promises")keeps the universal entry-point free of Node-only deps; bundlers that target the browser tree-shake this branch away, and the runtime guard prevents accidental invocation. - The returned array is sliced off the underlying
ArrayBufferso consumers never receive aBuffersubclass — useful when feeding the result into APIs that strictly type-checkUint8Array. - All thrown errors extend
SuaveplanErrorand round-trip through the standard redaction / wire-format adapters supplied by@suaveplan/error.