Last active
December 8, 2017 13:49
-
-
Save blrobin2/29204fa522025331119e82c385291036 to your computer and use it in GitHub Desktop.
A wrapping factory object for node.js createReadStream to promisify the read stream. Handles adding and removing event listeners for GC.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { createReadStream, ReadStream } from 'fs' | |
| class ReadStreamFactory { | |
| private readStream: ReadStream | |
| private promiseResolve: (stream: ReadStream) => void | |
| private promiseReject: (reason: Error) => void | |
| static createReadStream(filename: string): Promise<ReadStream> { | |
| const factory = new ReadStreamFactory(filename) | |
| return factory.promisifyReadStream() | |
| } | |
| private constructor(filename: string) { | |
| this.readStream = createReadStream(filename) | |
| this.onError = this.onError.bind(this) | |
| this.onReadable = this.onReadable.bind(this) | |
| } | |
| private promisifyReadStream(): Promise<ReadStream> { | |
| return new Promise((resolve, reject) => { | |
| this.promiseResolve = resolve | |
| this.promiseReject = reject | |
| this.addListeners() | |
| }) | |
| } | |
| private addListeners() { | |
| this.readStream.addListener('error', this.onError) | |
| this.readStream.addListener('readable', this.onReadable) | |
| } | |
| private onError(e: Error) { | |
| this.promiseReject(e) | |
| } | |
| private onReadable() { | |
| this.removeListeners() | |
| this.promiseResolve(this.readStream) | |
| } | |
| private removeListeners() { | |
| this.readStream.removeListener('error', this.onError) | |
| this.readStream.removeListener('readable', this.onReadable) | |
| } | |
| } | |
| // Usage | |
| (async () => { | |
| try { | |
| const stream: ReadStream = await ReadStreamFactory.createReadStream('filename.txt') | |
| } catch (e) { | |
| console.error(e.message) | |
| } | |
| }()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment