Writing First Node.js Server
July 22, 2011 Leave a comment
Since Node.js project has been announced in 2009 it has gained very big interest and popularity in developers’ world. I wanted to play with node.js and wrote very simple server. It takes two parameters from HTTP request from browser URL and response is the sum of those two numbers.
Firstly we need to import http module for creating instance of server:
var http = require('http');
We will need url module too for simplifying parsing of arguments from URL:
var url = require('url');
Then we need to create server instance with listener function:
http.createServer(function (req, res) { ... }).listen(7777);
This anonymous function is listener for client requests. It takes request and response objects as parameters. listen(7777) means that server is started on 7777 port at localhost.
For getting parameter values very easily in JSON object we will need just this:
var query = url.parse(req.url, true).query || {};
It is very simple and intuitive, as expected... In variable query we store object like this {a:1, b:2} if the request URL was ?a=1&b=2.
Let's check if both a and b are defined in query object and if yes then print sum if no then print warning in browser.
var rez = ""; if (query.a && query.b) { rez = (+query.a + +query.b) + ""; } else { rez = 'type url like "?a=1&b=2" to get sum from server!'; }
And finally there is whole code:
var http = require('http'); var url = require('url'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); var query = url.parse(req.url, true).query || {}; var rez = ""; if (query.a && query.b) { rez = (+query.a + +query.b) + ""; } else { rez = 'type url like "?a=1&b=2" to get sum from server!'; } res.end(rez); }).listen(7777);