Skip to content

Instantly share code, notes, and snippets.

Created August 14, 2012 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3348325 to your computer and use it in GitHub Desktop.
Save anonymous/3348325 to your computer and use it in GitHub Desktop.
{
"name": "app",
"version": "0.0.1",
"dependencies": {
"pg": "0.8.1",
"express": "2.5.x"
},
"engines": {
"node": "0.8.x",
"npm": "1.1.x"
}
}
/**
* Module dependencies.
*/
var express = require('express')
, pg = require('pg')
, sys = require('sys')
, conString = "postgres://username:password@host:5432/dbname";
var server = express.createServer(function(req, res) {
var start = new Date();
if(req.url != "/") {
res.writeHead(404);
return res.end("404'd")
}
var after = function(callback) {
return function(err, queryResult) {
if(err) {
res.writeHead(500, {"Content-Type" : "text/plain"});
return res.end("Error! " + sys.inspect(err))
}
callback(queryResult)
}
}
pg.connect(conString, after(function(client) {
client.query("SELECT COUNT(first_name) as count FROM users", after(function(result) {
client.query("SELECT first_name FROM users ORDER BY id DESC LIMIT 1", after(function(dateResult) {
var text = ["<html><head><title>Postgres Node Hello</title><body>",
"<p>I have been viewed ", result.rows[0].count, " times</p>",
"<p>Most recently I was viewed at ", (dateResult.rows.length !== 0 ? dateResult.rows[0].date : ""), "</p>",
'you can view the source <a href="http://github.com/brianc/node-postgres">on github</a>',
'<p>this page took ~',
(new Date())-start,
' milliseconds to render</p>',
"</body></html>"].join('')
res.writeHead(200, {"Content-Type": "text/html"})
res.end(text);
client.query('INSERT INTO users(first_name) VALUES($1)', ['Ann'])
}))
}))
}))
})
server.listen(3001)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment