Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1
Lesson 1: Getting started with Node.js CHAPTER 8 345

http.createServer(function (request, response) {
var url_parts = url.parse(request.url, true);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello ' + url_parts.query.name + '!\n');
console.log('Handled request from ' + url_parts.query.name);
}).listen(8080, 'localhost');
console.log('Server running at http://localhost:8080/');
}

exports.start = start;
In this example, the existing code has been wrapped with a start function. At the bottom
of the file, the start function is assigned to a start property on the exports object. The code is
saved to a hello.js file, and the module is created.
You use the new module just as you use other modules, by using the require function.
Create an index.js file and enter the following code to use your module.
var hello = require('./hello.js');
hello.start();

In this example, the module name is “./hello.js”. Notice that a relative path to the file is
used. The require function returns an object that is assigned to the hello variable, and then
the start method is executed.
After saving the file, you can run the code by executing the following at the command
prompt.
node index.js

This code works the same as the hello_ joe.js code except that this code uses your new
module.

Creating a Node.js package


A Node.js package, also known as an application, is a collection of modules with a manifest
that describes the package and its dependencies and can be publicly and privately published
for you and others to use. After you publish your package, you can use the node package
manager (npm) to install a package. The package can be installed in a single application
you’re creating or globally for use with many applications.
In this example, a call_counter.js module will be created, which will produce a console mes-
sage whenever its count_call function is executed. A simple_math.js module will be created,
which will contain an add function and a subtract function. An advanced_math.js module will
be created, which will contain multiply, divide, and Fibonacci functions. All the math functions
will be usable by other applications, but the call counter will remain private to the package,
so that each math function will call the count_call function. Although all these functions could
be placed in a single module, this example demonstrates the use of multiple modules.
These modules will be packaged so they can be published. After the package is published,
you and others can install the package and use it in other applications.

Key
Te rms

Free download pdf