Tutorials: NodeJS and Express
Tutorial 1: NodeJS: An Asynchronous World
Tutorial 2: Express: Middleware or more...
Tutorial 3: Understanding Routing in Express
Tutorial 4: Develop a Static File Server
Tutorial 5: Using HTTPS with Express
Tutorial 6: Develop a JSON API server
Tutorial 7: Use Templates and Views with Express
Tutorial 8: Integrating MongoDB
Tutorial 9: Testing Express Applications
Tutorial 10: Securing Express
- Its execution is fast (V8 JS engine being compined in C++)
- Promotes asynchronous coding style
- Same coding paradigm for front and back end.
Installing NodeJSThe simplest way is go to NodeJS website and click on the installer link. The site also provides other download options (binary download or installers for Mac and Linux flavours). For Windows make sure your machine has latest OS updates otherwise windows installer may have trouble in installing.
For Linux, nodeJS package manager (eg apt-get) is also available. The installer also installs node package manager (npm). Once installed you can check node version and npm version by typing node -v and npm -v respectively at the command prompt or shell.
First NodeJS ProgramYou can try your first the most famous "Hello World" program in nodeJS. Type the following script in notepad or any text editor and save the file as helloworld.js
To run this code type node helloworld.js at the shell prompt. If everything works well, you would see the output of the program similar to what is shown in the figure.
console.log() api is part of console built-in module in nodeJS. There are many inbuilt modules (or libraries) and globals defined in nodeJS. Apart from using built-in modules, you can use external modules.
Node Package Manager or npm helps you installing or managing node modules. The site www.npmjs.com lists the most starred packages used among NodeJS community.
Let us try to install and use colors module. The colors module gives colour style to your console output. Type npm install colors will download colors module from npm repository and install it. You can see a directory named 'node_modules' gets created where npm installs any package.
|npm install color|
See the following snippet showing how to use 'colors' node module:
Asynchronous Programming Approach
Asynchronous programming is another important aspect of NodeJS making it popular. Asynchronous functions take an additional argument(s) known as 'callback function' which are called when a particular event occurs. It is also called by another name 'continuation passing style' (CPS) programming. Let us write a simple nodeJS program to read a file asynchronously.
See the following snippet:
To read a file, we load another builtin node module 'fs' stands filesystem. This package provides File I/O routines available both synchronously and asynchronously.
The api fs.readFile reads file (named poem.txt) using UTF8 encoding. When its reading is complete, it invokes a callback function i.e. we call it onread( ). While the reading is going on, our program moves on to the next statement. That's why it displays "reading file..." message first. The call back function takes two parameters i.e. err and data. If there is an error in reading a file, it throws an error. Otherwise it displays the content using console.log( ).
Write a simple nodeJS web Server
NodeJS has built-in module 'http' which can be used to develop a simple web application server. Let us write and save the following snippet and run the node program (eg node myserver.js).
The first line loads 'http' built in node module. The second line createServer( ) creates a server object which listens for http requests at port 8080 (last line).
You can open a browser and type http://localhost:8080 to see the output. You will see server receives the connect event, it calls the callback function (line 3). The callback function has two arguments i.e. req (request object) and res (response object). As you know http communication is called request – response communication i.e. Browser (client) sends the request object and the server replies with response object (containing response headers and body text/binary). Here res.write (write method of response object) sends output string "Hi! Response from server".
The Line number 5, req.method tells what type of HTTP request method (or verb) is used by the client. The most common HTTP methods are GET, POST, PUT, DELETE and HEAD. Usually these correspond to develop read, create, update, delete (CRUD) etc. operations while developing WEB based APIs or services.
Let us write a small nodejs headless browser client which talks to our primitive server app. The node module 'http' also implements client communication.
Look at the following snippet which sends GET request to the server:
The method http.get( ) sends a get request the server (here to localhost at port 8080) and waits for the response data as a callback. When data is received, it displays using process.stdout.write method. You can use console.log( ) instead. The above snippet does not handle any error which may occur for different reasons e.g. Server is down.
Let us try another method http.request( ) which provides more control to http communication. In fact http.get( ) calls the default http.request( ).
Let us implement PUT request using http.request( ) method. Look at the following snippet.
http.request( ) accepts different options such as:
hostname: It is the hostname or ip address of the server.
port: port of the http server is listening to.
method: A string specifying HTTP verb. Its possible values can be GET, PUT, POST, DELETE etc.
path: requesting path of the url containing query parameters (if any).
headers: It is an object containing requesting headers as value name pairs. e.g. Here we use Content-Type header to inform the server that client is submitting form data.
http.request( ) method returns a request object (here we call it req). The req.write( ) method sends the form data to the server and wait for the response. When server replies, response event is triggered and the callback in http.request provides you a response object (here we call it resp). In the 'resp' object, we register for “data” event to receive the response body or content.
HTTP communication is the central core of web services. I suggest learn about various http methods, request and response architecture. I suggest go to httpbin.org and which helps you test your http client communication nodejs code.
In the next tutorial, we'll learn about ExpressJS, a third party module which abstracts away lot of http complexity and helps you focus on writing business logic.