HTML Dog
Skip to navigation

Node.js

Much of the code we’ve seen so far has been with a web browser in mind, using DOM APIs that are only available in that environment. But JavaScript has found its way to the other side of the client/sever divide in the form of Node.js (also known as just Node).

Node is a platform for building servers in JavaScript, built on Google’s V8 JavaScript engine. V8 is also found in the Chromium browser project and derivatives like Google Chrome.

Install

You can grab Node from nodejs.org. You’ll get npm in there too, which is the Node Package Manager, used to install others’ modules to make developing things easier.

Example

Node comes with a core set of modules, one of which is “http”, used to set up a web server. Here’s a simple HTTP server example that serves one page to all requests:


var http = require('http');

var server = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
})

server.listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

We grab the “http” module then create a server with a single callback function that serves all requests and then set it up to listen on localhost port 1337.