Recently I’ve been playing around with Node.js at work as the Mozilla Open Badges reference implementation uses it. After a while we realised it would be easier to deploy a PHP version, but I’ve carried on trying things with Node in my spare time.
As with all languages, the traditional ‘Hello World’ example is the best place to start, and here is the code for Node:
var http = require('http'); var server = http.createServer(function(request, response) { response.end("Hello World"); }); server.listen(8080);
Here’s what each line is doing:
var http = require('http');
We’re importing the HTTP library and creating a new object for use later in the script.
var server = http.createServer(function(request, response) {
This code create a server object from our existing HTTP object and passes an anonymous function as an argument. The request and response arguments will be populated when this function is called on each web page request.
response.end("Hello World");
This is the code which actually prints ‘Hello World’ to the browser, using the response parameter.
server.listen(8080);
Finally, we tell the server object to listen on port 8080. As we haven’t specified an IP address, the server will default to listening on the loopback address. Running this script and visiting http://127.0.0.1:8080 in a browser will result in the ‘Hello World’ message being displayed.