Chapter 5. Node and the Web
Node isn’t yet at the point where it can replace the fairly ubiquitous Apache/PHP killer combination, but it is gaining in popularity, especially considering the ease in creating cross-platform applications and the support it has among the big tech companies.
In this chapter, we’ll explore Node’s webby roots, including a more in-depth look at the HTTP module, as well as try our hand at creating a very simple static web server. We’ll also look at core Node modules that simplify the web development experience.
The HTTP Module: Server and Client
Don’t expect to use the HTTP module to re-create a web server with the sophistication of Apache or Nginx. As the Node documentation notes, it’s low-level, focusing on stream handling and message parsing. Still, it provides the foundational support for more sophisticated functionality, such as Express, covered in Chapter 10.
The HTTP module supports several objects, including http.Server
, which is what’s returned when you use the http.createServer()
function demonstrated in Chapter 1. In that example, we embedded a callback function to handle the web request, but we can also use separate events, since http.Server
inherits from EventEmitter
.
var
http
=
require
(
'
http
'
);
var
server
=
http
.
createServer
().
listen
(
8124
);
server
.
on
(
'
request
'
,
function
(
request
,
response
)
{
response
.
writeHead
(
200
,
{
'
Content
-
Type
'
:
'
text
/
plain
'
});
response
.
end
(
'
Hello
World
\
n
'
);
});
console
.
log
(
'
server
listening
on
8214
'
);
We can also ...
Get Learning Node, 2nd Edition 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.