Starting an HTTP server with Node.js

A very common use case for Node is building servers. Node makes it very simple to
create different types of servers. This can feel odd if you’re used to having a server
host your application (such as a PHP application hosted on an Apache HTTP server).
In Node, the server and the application are the same.
Here’s an example of an HTTP server that simply responds to any request with
“Hello World”:

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(3000);

console.log(‘Server running at http://localhost:3000/’);
Whenever a request happens, the function (req, res) callback is fired and “Hello
World” is written out as the response. This event model is akin to listening to an
onclick event in the browser. A click could happen at any point, so you set up a func-
tion to perform some logic to handle that. Here, Node provides a function that
responds whenever a request happens.
Here’s another way to write this same server to make the request event even more
explicit:

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

 

Leave a comment

Your email address will not be published. Required fields are marked *