Skip to content

Instantly share code, notes, and snippets.

@stepankuzmin
Created October 26, 2017 14:44
Show Gist options
  • Save stepankuzmin/fdb3f551912d605ecde35b88b89eda3e to your computer and use it in GitHub Desktop.
Save stepankuzmin/fdb3f551912d605ecde35b88b89eda3e to your computer and use it in GitHub Desktop.
NodeJS server with PostgreSQL streaming
const http = require('http');
const Pool = require('pg-pool');
const bluebird = require('bluebird');
const JSONStream = require('JSONStream');
const QueryStream = require('pg-query-stream');
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'data',
password: 'postgres',
poolSize: 20,
Promise: bluebird
});
const server = http.createServer(async (req, res) => {
try {
const client = await pool.connect();
const query = new QueryStream('SELECT * FROM generate_series(0, $1) num', [10000]);
const stream = client.query(query);
// release the client when the stream is finished
stream.on('end', () => client.release());
stream.pipe(JSONStream.stringify()).pipe(res);
} catch (error) {
console.error(error);
}
});
const hostname = '127.0.0.1';
const port = 3000;
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment