Added on Mar 15th, 2015 and marked as example nodejs server

With Node.js it is really easy to set up a simple server. Below I’ve collected some examples I’ve found and added a short explanation to each one.

Basic HTTP server

One of the most simple servers in Node.js is the following HTTP server. It will create a local server listening on port 8080. Every request triggers a single (and highly unoriginal) response.

basic-http-server.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!\n');
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');

Start the server and test it with curl:

$ node basic-http-server.js
$ curl http://127.0.0.1:8080

Server with a delayed response

This is a slight variation on the previous example. Instead of returning the response immediately and ending the connection, it will first tell you to have a bit more patience. After a short wait, it will send you the rest of the content. Notice that in the meantime the connection is kept open.

delayed-response.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Please hold on ...\n');
setTimeout(function(){
res.end('... Hello World!\n');
},2000);
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');

Start the server and check the time per request with the Apache benchmarking tool:

$ node delayed-response.js
$ ab -n 100 -c 100 http://127.0.0.1:8080/

If you use curl to request the URL, you will see the first response immediately, followed by the next one after 2 seconds. In the browser you won’t see anything until the entire response is received. This is just how the different clients deal with the server’s response.

Echo server

In this example we do not need the http module, instead we use the more low level net module. This server will wait for data that is sent and return it in uppercase.

echo-server.js
var net = require('net');
net.createServer(function(socket){
socket.write('You got something to say?\n');
socket.on('data', function(data){
socket.write(data.toString().trim() + ' ' + data.toString());
});
}).listen(8080);
console.log('Server running at 127.0.0.1 on port 8080');

Start the server and talk to it. Since this is not a HTTP server, we use the nc command.

$ node echo-server.js
$ nc 127.0.0.1 8080

Chat server

chat-server.js
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
// Application
var net = require('net');
var sockets = [];
net.createServer(function(socket){
sockets.push(socket);
socket.write('Welcome to the chat.\n');
socket.write('Start chatting ...\n');
socket.on('data', function(data){
for (var i = 0; i < sockets.length; i++){
if (sockets[i] === socket) continue;
sockets[i].write(data.toString());
}
});
socket.on('end', function(){
var i = sockets.indexOf(socket);
sockets.remove(i);
});
}).listen(8080);
console.log('Server running at 127.0.0.1 on port 8080');

Start the server and connect to the server from at least two terminal windows. Now you can talk to each other.

$ node chat-server.js
$ nc localhost 8080

Static file server

static-file-server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var appConfig = {
staticPath: __dirname
};
http.createServer(function(req,res){
var path = appConfig.staticPath + url.parse(req.url).pathname;
fs.exists(path,function(exists){
if (exists) {
fs.readFile(path,function(err,data){
if (err) throw err;
res.end(data)
});
}
else {
res.statusCode = 404;
res.end('404 Not Found. Sorry.\n');
}
});
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');

Start the server and test it by requesting several URLs. If the requested file doesn’t exist, it will return a 404 status code and corresponding response message.

$ node static-file-server.js
$ curl http://127.0.0.1:8080/static-file-server.js
$ curl http://127.0.0.1:8080/not-found

Note: These are just simple examples. Probably you shouldn’t use it in real world code. However, they are really useful in understanding how the basics of Node.js work and even how servers and clients interact with each other.