Getting Started with Node.js
Written by Ian Elliot   
Thursday, 12 October 2017
Article Index
Getting Started with Node.js
The Server

The Server

The program has successfully printed a single line of text to the console. This may not be a very inspiring start but it is an example of JavaScript running out side of the browser and you can now start to write applications that access the file system on the local machine, do database lookup and so on.

However this isn't really what Node.js is all about.

The idea is that you write JavaScript to serve data to a client web browser. You can do this in a number of ways but the simplest is to start a web server.

First you need to create a web server and this requires the JavaScript module that defines it:

var http = require('http');

The require function loads the module if it hasn't already been loaded and returns an object which provides its functionality.

Now we have an http object that has a set of methods, events and properties that let us work with HTTP requests. Its most important method is createServer which creates a server object that can be set to listen on any IP address port combination and when it gets a request it will run a function that you specify. You can define the response function anyway that you like but for such a simple example it might as well be defined in the call to createServer:

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

The response function accepts two parameters:

  • The req parameter is an object that represents all of the information about the request - e.g. the URL, the headers and so on.

  • The res parameter is a writable stream that is used to send the response back to the client.

In this case all that happens is that we write a minimal HTTP header and a single text line saying "Hello World".

Finally to make the server active we use its listen method:

webServer.listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');

The listen method in this case assigns port 1337 to the server and we print a console message that acts as a reminder of this.

To see the program in action simply start up a browser and enter the URL http://127.0.0.1:1337/ and you should see the hello world message.  

Events

Notice that the program doesn't end after the console.log command. The webServer object still exists and is waiting for a client to make a request so that it can call the response function. To stop the web server simply press Ctrl-C.

This is an example of event driven programming and if you have used almost any modern programming language that has a graphical UI you will have encountered it before.

When you create an even driven UI you place button object on a form and write a click event handler for it. When you run the program it doesn't stop after creating the button. Instead it waits until the button is clicked and then handles the event by invoking the event handler.

Node.js works in the same way - you created the web server object and specified an event handler. This waits for the event and calls the handler which in this case supplies the response to the client.

To show you that this really is how things are working let's create two web servers listening on two different port numbers -

var http = require('http');
var webServer1=http.createServer(
         function (req, res) {
           res.writeHead(200,
            {'Content-Type': 'text/plain'});
           res.end('Hello World from server 1\n');
         });
var webServer2=http.createServer(
         function (req, res) {
           res.writeHead(200,
            {'Content-Type': 'text/plain'});
           res.end('Hello World from server 2\n');
         });

webServer1.listen(1337, "127.0.0.1");
console.log('Server 1 running at
                http://127.0.0.1:1337/');

webServer2.listen(1338, "127.0.0.1");
console.log('Server 2 running at
                http://127.0.0.1:1338/');


Now we have one server listening for a connection on port 1337 and another on port 1338. If you point a browser at the first address you will see the first message and if you point it at the second address you will see the second message.

You can think of the two web servers as being like two buttons each with a distinct event handler waiting for a TCP connection to occur on their particular port.

Having two web servers on different ports isn't a likely operating scenario, but you can see how easy it is to "bind" a server to a port. This works just as easily if you want to work lower down the stack with a socket say. This ease of setting up asynchronous listeners for communications protocols is one of the strong points of Node.js.

Reading the headers

Now you have seen the basic operating principle of Node.js you can probably work out how to create more useful programs.

As a slightly larger final example consider the problem of sending back the headers in a request to the client.  In this case we can write a standalone response function:

var http = require('http');
var response=function(req,res){

The minimum HTMLwe have to write to get a page to display is the <html> tag so we can start the page off with just this:

res.writeHead(200, {
              "Content-Type": "text/plain"});
res.write('<html>');

Next we get the headers that were sent to the server as an object with one property for each header:

var headers=req.headers;

Next we use a for loop to step though each one in turn and send the header name and value to the output page:

for(h in headers){
 res.write(h);
 res.write('->');
 res.write(headers[h]);
 res.write(' <br/> ');
}

Finally we close the <html> tag and send the response to the client:

 res.write('</html>');
 res.end();
};

To actually create the server we need:

var webServer=http.createServer(response);
webServer.listen(1337, "127.0.0.1");
console.log('Server 1 running at
              http://127.0.0.1:1337/');

That is all there is to it. If you start the new program running you can point a client browser at it to see the headers sent to the server.

The example could have been written in a much more compact style by defining the response function in place and grouping the write methods into fewer calls but this doesn't fit the purpose of an example.

Where next?

Now you have seen Node.js in action how to expand what you are doing should be obvious. There are lots of modules to explore in the documentation, including file system handling, cryptography, sockets and so on. Node.js is still short of a lot of capabilities in the official modules but there are also third party modules that fill many of the gaps - mysql access, HTML parsing and various web frameworks.

What Node.js is good at, however, is when you want to create a web application that needs to implement Ajax like updates or where you need to communicate via custom protocols with the client. 

You can't deny that it's an interesting way to do things and the advantage of being able to use the same language at both ends of a transaction is worth a lot.

A Programmers Guide To Languages

languagecover

Contents

  1. Octave
  2. Scratch 3 *revised
  3. Node.js *revised
  4. App Inventor 2 *revised
  5. Getting Started With .NET IL
  6. NetLogo *revised
  7. Small Basic  *revised
  8. TypeScript *revised
  9. Google Apps Script
  10. Guide to F#
  11. Python
  12. Google's Go
    1. A Programmer's Guide To Go With Visual Studio Code *revised
    2. A Programmer's Guide To Go Part 2 - Objects And Interfaces *revised
    3. A Programmer's Guide To Go Part 3 - Goroutines And Concurrency *revised
  13. Guide to F#
  14. The Prolog Way ***NEW!
  15. Ruby
    1. Object-Oriented Approach
    2.    A Functional Language

More Information

Node.js

 nodeicon

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

 

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info

 

Banner


JavaScript Jems - Objects Are Anonymous Singletons

JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way.  In particular, every object can be regard [ ... ]



JavaScript Canvas - Typed Arrays

Working with lower level data is very much part of graphics. This extract from Ian Elliot's book on JavaScript Graphics looks at how to use typed arrays to access graphic data.


Other Articles



Last Updated ( Thursday, 12 October 2017 )