Chapter 2. A Simple Node.js Framework

In the previous chapter, I presented a development environment along with a general education about how to use it to execute a conversion. In this chapter, we will start using that development environment and begin the actual conversion.

An HTTP Server

In PHP, a PHP file represents an HTML page. A web server, such as Apache, accepts requests and if a PHP page is requested, the web server runs the PHP. But in Node.js, the main Node.js file represents the entire web server. It does not run inside a web server like Apache; it replaces Apache. So, some bootstrap Node.js code is needed to make the web server work.

The httpsvr.njs file was presented as an example in the previous chapter. Here’s the Node.js code for the httpsvr.njs file:

var http = require('http');
var static = require('node-static');
var file = new static.Server();

http.createServer(function (req, res) {
 file.serve(req, res);
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

How does this work?

As described in the previous chapter, the Node.js require() API function makes a module available for use. The first two lines show a built-in module and an external module:

var http = require('http'); // built-in module
var static = require('node-static'); // external module

If you installed Node.js and followed the examples in the previous chapter, the node-static npm package, which contains the node-static external module, will already be installed. If not, install ...

Get Node.js for PHP Developers 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.