Use the to function (aliased as copyTo) to create a Readable stream from a PostgreSQL table.
Important: Do not use pool.query(). You must acquire a client via pool.connect() and call client.query() on that client to support the custom query objects required for streaming.
Callback Pattern
var { Pool } = require('pg')
var { to as copyTo } = require('pg-copy-streams')
var pool = new Pool()
pool.connect(function (err, client, done) {
var stream = client.query(copyTo('COPY my_table TO STDOUT'))
stream.pipe(process.stdout)
stream.on('end', done)
stream.on('error', done)
})
Async/Await Pattern
import { pipeline } from 'node:stream/promises'
import pg from 'pg'
import { to as copyTo } from 'pg-copy-streams'
const pool = new pg.Pool()
const client = await pool.connect()
try {
const stream = client.query(copyTo('COPY my_table TO STDOUT'))
await pipeline(stream, process.stdout)
} finally {
client.release()
}
await pool.end()
import { pipeline } from 'node:stream/promises'
import pg from 'pg'
import { to as copyTo } from 'pg-copy-streams'
const pool = new pg.Pool()
const client = await pool.connect()
try {
const stream = client.query(copyTo('COPY my_table TO STDOUT'))
await pipeline(stream, process.stdout)
} finally {
client.release()
}
await pool.end()