Skip to content

Instantly share code, notes, and snippets.

@mihaerzen
Last active October 17, 2023 15:31
Show Gist options
  • Save mihaerzen/737e240d6db6332cbacd83a8eedd1cc5 to your computer and use it in GitHub Desktop.
Save mihaerzen/737e240d6db6332cbacd83a8eedd1cc5 to your computer and use it in GitHub Desktop.
sqlite3 readable stream
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