Node.js

What is Node.js?

Node.js is a software package consisting of a JavaScript engine and a number asynchronous input / output (I/O) libraries. It allows you to run JavaScript on the command line, outside of your browser.

The JavaScript engine used is the V8 JavaScript engine, which also powers the Chrome Browser. The I/O libraries allow Node.js to interface with files or network devices in an asynchronous manner. This allows Node.js to be used as a fast, lightweight, event-based web server.

Up and Running

To get started, downloading the Node.js package for your platform on the Node.js website. You can also get Node.js through your favorite package manager on Mac OS X or Linux distro.

After you’ve installed Node.js, run it by opening a command prompt and typing node. You get dropped into a REPL. The node.js REPL works exactly the same as Chrome’s REPL, so you can run any of your JavaScript commands here.

Node.js can also be used to run files. Try creating a file called hello.js containing console.log("hello world"). Now run node hello.js. Node.js will open the file, run your program and exit.

Loading modules

Node.js provides a mechanism for importing external libraries using the command require.

Earlier we saw that a JavaScript library should export a single global object, and that all functionality should be provided as properties or objects of that object. For instance, the jQuery library exports a single object that is named jQuery or $, and the d3 library exports a single object that is named d3.

Node.js uses that idea. To load a module, use the require command:

var http = require("http");

This loads the http library and the single exported object available through the http variable. By convention, the variable name is the same as the module name, but you can also pick any variable name you like, e.g. var otherName = require("http").

The system that Node.js uses behind the scenes to load modules is called CommonJS. If you write your own library for node, your code should conform to the CommonJS specifications.

Installing modules

Where do modules come from? Some modules, such as http, are installed as part of the standard Node.js library. Other user-contributed modules have to be downloaded and installed. Recent versions of Node.js come with a package manager called npm, which allows you to download and install modules easily. To install a package, run npm install package_name on the command line.

Another way of installing modules is by installing them as part of the application. If you place a file called package.json in the same folder as your application, and then run npm install in that folder, npm will extract the list of dependencies from package.json, and then install them locally in the application. Here’s what a sample package.json file will look like:

{
	"name": "chirps",
	"description": "A social media website for sharing short messages",
	"version": "0.0.1",
	"engines": {
		"node": "0.8.x",
		"npm": "1.2.x"
	},
	"dependencies": {
		"express": "3.2.x",
		"ejs": "0.8.x"
	}
}

Your First HTTP Server

Let’s create a HTTP server! Copy the following code (taken from the Node.js website) into a file, and then run it using Node.js.

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

The code first loads the HTTP library. It then creates a new server, and sets a callback function that will be called whenever a browser connects to the server. The server is then set to listen to incoming connections at 127.0.0.1:1337 using the listen command.

Here’s how the callback function works. The server will call the provided callback function whenever it receives a request, and it will pass in two useful objects as parameters. The callback function is passed req, the request object, and res, the response object. req contains information about the browser’s request, such as the path requested. res is an object that should be used to send the server’s response using the writeHead and end methods. In the example above, the callback method simply prints the words “Hello World” back to the browser.

The problem with the HTTP library is that it is very low level. It allows you to operate directly on the HTTP request and response objects, but it doesn’t give you any higher-level abstrations that would help you build a web application.

Here are some drawbacks. You only get to specify a single callback function. You have to retrieve the URL from the req parameter and match it with your list of available URLs manually. You need to set response headers manually.

Web Frameworks

A web framework is a collection of tools and libraries designed for web applications. A web framework can make our life easier by handling common functionality that is used in web applications such as routing, templating, sessions, etc. Examples of frameworks are Rails and Django.

A web microframework is like a web framework, but provides a more minimalistic set of tools. Examples include Sinatra and Flask. Node.js has its own popular microframework called Express, which will see next.

Express

Here’s what the same application looks like in Express.

var express = require("express");
var app = express();
app.get("/", function(req, res) {
	res.send("Hello world!");
	res.end();
}).listen(1337);
console.log('Server running at http://127.0.0.1:1337/');

In this example, we loaded the Express module, created an application, defined a new route, and then made the server listen for new connections.

The application is very similar to the old server, but notice the improvements. We can now specify that our handler should handle only the GET method on the ”/” url. We also got rid of having to fiddle around with the headers on the response.

Routes

We can create more routes for the application using the get and post methods. get creates routes for the HTTP GET method, while post creates routes for the HTTP POST method. Both get and post take the URL as the first parameter and a callback function as the second. The callback function is passed req, the request object, and res, the response object. req contains information about the browser’s request, such as the path requested. res is an object that should be used to send the server’s response using the send and end methods.

var express = require("express");
var app = express();

app.get("/hello", function(req, res) {
	res.send("Hello!");
	res.end();
});

app.get("/world", function(req, res) {
	res.send("World!");
	res.end();
});

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

Parameters

You can get query parameters in the callback functions. For instance, you can access GET parameters through the req.query object. Consider the following server code:

var express = require("express");
var app = express();
app.get("/", function(req, res) {
	res.send("Hello, " + req.query.name + "!");
	res.end();
}).listen(1337);
console.log('Server running at http://127.0.0.1:1337/');

If you run the server and visit http://127.0.0.1:1337/?name=John, you will see that the page changes to reflect the value of the name parameter.

Static Files

We can use Express as a static file server as follows:

var express = require("express");
var ejs = require("ejs");
app.use(express.static(__dirname + "/public"));
app.listen(1337);

This tells Express to use /public as the directory from which files are served. If the server receives a request that does not match any of the routes, but matches a file in that directory, Express will respond by sending that file. For instance, if we create a file at public/hello.html, then we can view it by going to http://127.0.0.1:1337/hello.html.

Views

Views allow us to specify a template for a page, and then dynamically fill in information to the page.

var express = require("express");
var app = express();

app.set("view engine", "ejs");
app.set("views", __dirname + "/views");

app.get("/", function(req, res) {
	res.render("hello", {"greeting": Hello world!});
}).listen(1337);

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

We use the set command to select EJS as the templating engine. there are other templating engines engines available, such as Jade, but we pick EJS because it is the simplest. We then set the folder to the /views directory.

In the handler for /, we simply call the render method, specifying the name of the template to use, and the data that should be passed to the template. Any data that is passed to the template will become local variables within the variables.

The contents of /views/hello.ejs are as follows. Notice the use of the <%= greet %> tag, which causes the value of greet to be printed at the appropriate position:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Hello World</title>
</head>
<body>
	<h1><%= greet %></h1>
</body>
</html>