A simple server with Node.js

To see an example of just how lightweight Node can be, let's take a look at some sample code that starts up an HTTP server and sends Hello World to a browser:

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

A few basic lines of code are all it takes to write a complete Node application. Running it with a simple Node app.js command will launch an HTTP server that is listening on port 8080. Point any browser to http://localhost:8080, and you will see the simple output Hello World on your screen! While this sample app doesn't actually do anything ...

Get Web Development with MongoDB and NodeJS - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.