forked from brianc/node-postgres
- Notifications
You must be signed in to change notification settings - Fork 0
Example
MegaJ edited this page Aug 17, 2016
·
31 revisions
You'll need to do npm i pg before you run this example. Make sure node-postgres is installed at minimum 6.0.0.
varhttp=require('http');varPool=require('pg').Pool;// by default the pool will use the same environment variables// as psql, pg_dump, pg_restore etc:// https://www.postgresql.org/docs/9.5/static/libpq-envars.html// you can optionally supply other valuesvarconfig={//host: 'localhost',//user: 'foo',//password: 'bar',//database: 'my_db',};process.on('unhandledRejection',function(e){console.log(e.message,e.stack)})// create the pool somewhere globally so its lifetime// lasts for as long as your app is runningvarpool=newPool(config)varserver=http.createServer(function(req,res){varonError=function(err){console.log(err.message,err.stack)res.writeHead(500,{'content-type': 'text/plain'});res.end('An error occurred');};pool.query('INSERT INTO visit (date) VALUES ($1)',[newDate()],function(err){if(err)returnonError(err);// get the total number of visits today (including the current visit)pool.query('SELECT COUNT(date) AS count FROM visit',function(err,result){// handle an error from the queryif(err)returnonError(err);res.writeHead(200,{'content-type': 'text/plain'});res.end('You are visitor number '+result.rows[0].count);});});});pool.query('CREATE TABLE IF NOT EXISTS visit (date timestamptz)').then(function(){server.listen(3001,function(){console.log('server is listening on 3001')})})