Created
October 26, 2017 14:44
-
-
Save stepankuzmin/fdb3f551912d605ecde35b88b89eda3e to your computer and use it in GitHub Desktop.
NodeJS server with PostgreSQL streaming
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
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