Read a chunk from a file
npx @tessl/cli install tessl/npm-read-chunk@5.0.0Read Chunk is a Node.js utility library that provides both asynchronous and synchronous APIs for reading specific chunks of data from files. It eliminates the boilerplate code typically required with Node.js built-in fs methods by handling file descriptor management automatically and returning data as Uint8Array buffers.
npm install read-chunkimport { readChunk, readChunkSync } from "read-chunk";For TypeScript projects:
import { readChunk, readChunkSync, type Options } from "read-chunk";import { readChunk, readChunkSync } from "read-chunk";
// Asynchronous usage
const chunk = await readChunk('foo.txt', {
length: 3,
startPosition: 1
});
console.log(chunk); // Uint8Array containing the chunk data
// Synchronous usage
const chunkSync = readChunkSync('foo.txt', {
length: 3,
startPosition: 1
});
console.log(chunkSync); // Uint8Array containing the chunk dataRead a chunk from a file asynchronously using Node.js file descriptor operations.
/**
* Read a chunk from a file asynchronously
* @param filePath - The path to the file
* @param options - Configuration options for the read operation
* @returns Promise resolving to the read chunk as Uint8Array
*/
function readChunk(filePath: string, options: Options): Promise<Uint8Array>;Usage:
import { readChunk } from "read-chunk";
// Read 10 bytes starting from position 5
const chunk = await readChunk('/path/to/file.txt', {
length: 10,
startPosition: 5
});
// Read from beginning of file (startPosition defaults to 0)
const header = await readChunk('/path/to/binary-file.bin', {
length: 1024
});Read a chunk from a file synchronously using Node.js file descriptor operations.
/**
* Read a chunk from a file synchronously
* @param filePath - The path to the file
* @param options - Configuration options for the read operation
* @returns The read chunk as Uint8Array
*/
function readChunkSync(filePath: string, options: Options): Uint8Array;Usage:
import { readChunkSync } from "read-chunk";
// Read 10 bytes starting from position 5
const chunk = readChunkSync('/path/to/file.txt', {
length: 10,
startPosition: 5
});
// Read from beginning of file
const header = readChunkSync('/path/to/binary-file.bin', {
length: 1024
});interface Options {
/** The number of bytes to read */
readonly length: number;
/**
* The position to start reading from (defaults to 0)
* Can be specified as number or bigint for large file positions
*/
readonly startPosition?: number | bigint;
}Both functions handle file descriptor cleanup automatically using try/finally blocks. File system errors (such as file not found, permission denied, or invalid file paths) are propagated to the caller as native Node.js fs errors.
Common error scenarios:
Uint8Array for consistent binary data handling across all platformsnode:fs, node:fs/promises)import/export syntax)