Last active
December 2, 2023 12:56
-
-
Save alexreardon/0a71e91891c02cc13d31c7a5c4ef8c75 to your computer and use it in GitHub Desktop.
rxjs file stream
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
// @flow | |
import fs from 'fs'; | |
import { Observable } from 'rxjs'; | |
type Options = { | |
highWaterMark: number, | |
encoding: string, | |
} | |
const defaultOptions: Options = { | |
// number of bits to read at a time | |
highWaterMark: 1, | |
encoding: 'utf8', | |
}; | |
export default (path: string, options?: Options = defaultOptions) => | |
Observable.create((observer) => { | |
const file$ = fs.createReadStream(path, options); | |
file$.on('data', (chunk) => observer.next(chunk)); | |
file$.on('end', () => observer.complete()); | |
file$.on('close', () => observer.complete()); | |
file$.on('error', (error) => observer.error(error)); | |
// there seems to be no way to actually close the stream | |
return () => file$.pause(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! If you create the read stream using a file descriptor instead of a path, you can call
fs.close(fd)
. This closes the opened file descriptor and in turn closes the read stream (which will emit aclose
event).