Last active
October 17, 2023 15:31
-
-
Save mihaerzen/737e240d6db6332cbacd83a8eedd1cc5 to your computer and use it in GitHub Desktop.
sqlite3 readable stream
This file contains 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 sqlite, { Statement } from 'sqlite3' | |
import { Readable, ReadableOptions } from 'stream' | |
interface Props extends ReadableOptions { | |
dbPath: string | |
query: string | |
} | |
export class SqliteReadable extends Readable { | |
private stmt: Statement | |
constructor({ dbPath, query, ...readableOptions }: Props) { | |
super(readableOptions) | |
const db = new sqlite.Database(dbPath) | |
this.stmt = db.prepare(query) | |
this.on('end', () => | |
this.stmt.finalize(() => { | |
db.close() | |
}), | |
) | |
this.on('error', console.error) | |
} | |
_read() { | |
this.stmt.get((err, result) => { | |
err ? this.emit('error', err) : this.push(result || null) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment