Build web apps with Node
Contents
Web Server
- Create a file in your project directory: touch http-server.js
- Open the new file in your code editor: atom http-server.js
- Write the following code in the file:
var http = require('http');
var server = http.createServer(function(request, response) {
response.end('Hello World');
});
server.listen(8000);
- Save the file.
Go to the command line and run:
node http-server.js. Now, go to the browser and visit http://localhost:8000. You should see the message 'Hello World' printed in the browser.
How it works:
In order to use any module in node, we need to use the require() statement. If its a core module (like http), we can simply require() it without any installation step. After getting a reference to the http module through require(), we use the createServer() function for the http module to create an instance of an http server and pass it the function (also called callback function) that will be called any time a request is made to this server. We then call the listen() function on the server object returned by createServer() to start the node server.
More details on the http module and the API are available here
Web Client
Goal: A web client that connects to a web server and prints the contents returned by the server.
- Create a file in your project directory: touch http-client.js
- Open the new file in your code editor: atom http-client.js
- Write the following code in the file:
var http = require('http');
var url = 'http://localhost:8000';
http.get(url, function(response) {
response.on('data', function(d) {
console.log(d.toString());
});
});
- Save the file.
Go to the command line & first run your web server with the command node http-server.js. Open another command line window and run your web client with the command node http-client.js. This will display 'Hello World' in the command line for the web client. Note: Runing the web client in this way is similar to going to the browser and visiting the url http://localhost:8000, as the browser is a web client too!
How it works:
Much like the web server, in order to make a http client we will need to require() the http module at start. Then we use the get() api call of the http module with 2 parameters, the first is the url to connect to and the second is a callback on how to handle the response from the server.