344 CHAPTER 8 Websites and services
var http = require('http');
var url = require('url');
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/');
This application was saved to hello_ joe.js. Run the application and then launch the
browser. Navigate to the following URL.
http://localhost:8080/?name=Joe
When the request is received, a response is sent, and a message is logged to the console
window, as shown in Figure 8-2. Try different names and notice that you get a personalized
response.
FIGURE 8-2 Creating a personalized response with Node.js
Creating a Node.js module
In the previous examples, you used the require function to load modules, which provide code
reuse when adding functionality to Node.js. You can create your own module by wrapping
your code in a function and exporting it so it can be called from other code, as follows.
var http = require('http');
var url = require('url');
function start(){