Skip to content
brianc edited this page Dec 3, 2010 · 17 revisions

live example

This app is running live right here

You'll need to first "create table visits (date date)" in your postgres database

var sys = require('sys');
var http = require('http');
var pg = require('pg')
var connectionString = "postgres://postgres:abcd@localhost:5432/postgres";

var server = http.createServer(?(req, res) {
  if(req.url != "/") {
    res.writeHead(404);
    return res.end("404'd")
  }
  var after = ?(callback) {
    return ?(err, queryResult) {
      if(err) {
        res.writeHead(500, {"Content-Type" : "text/plain"});
        return res.end("Error! " + sys.inspect(err))
      }
      callback(queryResult)
    }
  }
  
  pg.connect(connectionString, after(?(client) {
    client.query("SELECT COUNT(date) as count FROM visit", after(?(result) {
      client.query("SELECT date FROM visit ORDER BY date DESC LIMIT 1", after(?(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[0].date, "</p>",
                    'you can view the source <a href="http://github.com/brianc/node-postgres">on github</a>',
                    "</body></html>"].join('')
        res.writeHead(200, {"Content-Type": "text/html"})
        res.end(text);
        client.query('INSERT INTO visit(date) VALUES($1)', [new Date()])
      }))
    }))
  }))
})

server.listen(3001)
Clone this wiki locally