PostgreSQL and Node.js – 100% JavaScript Adventure

This is a log of every step I will take to create a 100%-JavaScript application back to front.

Hardware: Windows 7 64bit Home Edition ASUS laptop with Intel P6100 CPU @2.0GHz, 4GB RAM, 320GB HDD

Oracle VirtualBox 4.2.12
Ubuntu 12.04.2 – Long term support
Downloaded 32bit ISO image – laptop does not support 64bit virtualisation 🙁
Virtual machine: 1 CPU, 1GB RAM, 20GB HDD, with bridged network, boot CD first to use ISO image
Minimal install with OpenSSH server

Update repositories and upgrade base system

To use PostgreSQL Apt repository, follow: http://wiki.postgresql.org/wiki/Apt

Edit source list:

and add append this line:

Save and exit.
Import repository key and update.

This will also install GCC and many related packages to compile code.

Install Node.js – refer to http://nodejs.org/

Install git if you want to work with github or bitbucket etc.

I think my development environment is ready. Next step is to create an application.

Let’s prepare the database server. Create a database user and a database owned by that user.

Make sure local connections are allowed for local users:

And execute this code to create a table and save couple of records in our sample database.

Install Express for Node globally:

Clone my sample application if you want to.

One of the dependencies is “pg” which is the PostgreSQL module for Node.js.

Install any dependencies.

Sample code: app.js

And run the (server) application.

On your browser, request the test page:

Output should be:

You can see the output in JSON including the info field which uses JSON field type (added in PostgreSQL 9.2).

Lovely!

Next step is to create functions in PostgreSQL using PL/V8. This way I want to keep my server very lightweight and fast. I like my database server as the data gate keeper 🙂

Basically, almost every request will execute:

And each function will output a row or many rows which will be served as part of the response.

https://github.com/muratyaman/pgnode

Next: Part 2

Leave a Comment