smartstream/ts/smartstream.nodewebhelpers.ts

34 lines
999 B
TypeScript
Raw Permalink Normal View History

import { createReadStream } from 'fs';
/**
* Creates a Web ReadableStream from a file.
*
* @param filePath - The path to the file to be read
* @returns A Web ReadableStream that reads the file in chunks
*/
export function createWebReadableStreamFromFile(filePath: string): ReadableStream<Uint8Array> {
const fileStream = createReadStream(filePath);
return new ReadableStream({
start(controller) {
// When data is available, enqueue it into the Web ReadableStream
fileStream.on('data', (chunk) => {
controller.enqueue(chunk as Uint8Array);
});
// When the file stream ends, close the Web ReadableStream
fileStream.on('end', () => {
controller.close();
});
// If there's an error, error the Web ReadableStream
fileStream.on('error', (err) => {
controller.error(err);
});
},
cancel() {
// If the Web ReadableStream is canceled, destroy the file stream
fileStream.destroy();
}
});
}