Using Node JS and Couch DB Stack for Web Dev
With all the recent hype of http://nodejs.org/ I thought it'd be worth a go. Very crude example but does what it says on the tin, uses Node JS to create a server and when requested gets data from Couch DB and displays it in a web page.
You can download and install Node from http://nodejs.org/#downloadI used the OSX Couch DB install from http://janl.github.com/couchdbx/ but see http://couchdb.apache.org/ for other platforms. I've setup a DB on called monkey with 2 records, it can be reached at http://127.0.0.1:5984/monkey/_all_docs.
/>
You'll need 2 files for this demo - a html template, template.html (used for the output) and the js file (all the clever bits).
Simply copy/paste the following code to a .js file next to template.html and executing $ node my-file.js. Go to your browser and type in http://127.0.0.1:8001/ to see the page.
var sys = require("sys"),
http = require("http");
posix = require("posix");
http.createServer(function (req, res) {
res.sendHeader(200, {'Content-Type': 'text/html'});
var couch = http.createClient(5984, "localhost");
var request = couch.get("/monkey/_all_docs", {"host": "localhost"});
var template = posix.cat('template.html').wait();
request.finish(function (response) {
response.setBodyEncoding("utf8");
var response_body_str = "";
if(response.statusCode == 200){
response.addListener("body", function (chunk) {
response_body_str += chunk;
});
response.addListener("complete", function() {
response_body = JSON.parse(response_body_str);
template = template.replace("__total_records__",response_body.total_rows);
template = template.replace("__json__",JSON.stringify(response_body));
res.sendBody(template);
res.finish();
});
}
else sys.puts('invalid responce');
});
}).listen(8001);
sys.puts('Server running at http://127.0.0.1:8001/');
The html template:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Node JS + Couch DB Demo</title>
<style>
body{font-family:arial; font-size:1em; line-height:1.2em;}
h1{font-size:1.3em;}
</style>
</head>
<body>
<h1>Node JS + Couch DB Demo</h1>
<p><strong>Total Records: __total_records__</strong><p>
<pre>
__json__
</pre>
</body>
</html>
This was a rather quick hack to see what Node was capable off so I'll be following this up with something more useful (and less hacky) soon.