Node.js Tutorial Series - Getting Started

Posted by: Ravi Kiran , on 6/17/2015, in Category Node.js
Views: 27403
Abstract: Our Node.js tutorial series for beginners and experienced developers will help you start building real-time applications.

Ryan Dahl, the author of Node.js had introduced it in his talk at JSConf 2009 and he received a standing ovation from the audience for his work. Node.js is not a library. It is a platform for building server based applications using JavaScript. The official site for Node.js defines it as follows:

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

 

Written in C++ and JavaScript, Node.js uses the V8 JavaScript engine (the JavaScript engine used by Chrome browser) for execution. Node.js installers are available for Windows, Linux and Mac.

Asynchronous Execution and Event Loop

Node.js treats I/O and network operations as slower operation and runs them asynchronously. So it doesn’t wait for the operation to complete before picking the next task in the queue. Every asynchronous operation accepts a callback function. The callback is called with two parameters once the operation is complete:

  • The first parameter contains details of error, if the execution is failed
  • The second parameter is the data returned upon successful execution of the operation

Unlike other server platforms, Node.js doesn’t have multiple threads to process the request. It has just one thread to take care of all the requests. As already stated, Node.js uses the V8 JavaScript engine for execution. Hence, the way JavaScript executes on this platform is much similar to the way it works on a browser.

Though Node.js runs on a single thread, it is capable of responding to a huge number of parallel requests. The Event loop mechanism of the platform makes this possible. The following figure illustrates how event loop works:

node-event-loop

Event loop is also used by the browsers to handle asynchronous operations. Following listing describes the request-response cycle illustrated in the above figure:

1. Clients send request to the Node.js Server

2. The requests are either picked up by the event loop or, are asked to wait in a queue for the event loop to be free if it is currently handling another request

3. If the operation requested by the client has to be executed asynchronously, the task is delegated to worker threads and event loop picks the next task from the queue

4. If a worker thread finishes its task, it sends a notification to the event loop via a callback and it passes the result of the operation to this function

Package Management

Many programming languages and platforms have a system in place which allows them to install and manage external 3rd party modules, which extend the utility of the platform. Node.js is no different and comes with a package manager called Node Package Manager (NPM). It gets installed along with the installer of Node.js and can be used from command prompt. By default, NPM points to the global NPM repository (http://www.npmjs.org) and is able to install any package that is already available on this repository.

If you’re not sure of the name of the package you want to install, use the npm search command as follows:

npm search <package name>

The Node.js team has built the most common packages and made them available over NPM. The community has also been actively contributing repositories to NPM. All available packages can be browsed on the official site.

Module System

Node.js shares some perceived limitations with JavaScript. One of them is there is no way to share modules between the browser, server and other frameworks. Node.js solves this problem by using the CommonJS module system. CommonJS is an open source module system designed by some developers and is used by several JavaScript based projects.

CommonJS module system is synchronous in nature. It allows modules to export data and this data is made available to the importing modules. Just like any other module system, it provides a nice way to structure code written in Node.js and helps in building apps based on large code base.

Note: Another alternative to CommonJS is RequireJS which is a JavaScript file and module loader and has been developed specifically for the browser environment.

Writing a Hello World Node.js Application

Now that you know what Node.js is and how it works, let’s write a simple Hello world application. Before you start writing the app, make sure to install Node.js by downloading the installer for your OS from the official site.

Create a new folder at your favorite location and name it HelloWorldNode. Create a new file inside the folder and change name of the file to server.js. Open this file in any text editor and type in the following code:

var http = require('http');
http.createServer(function(request, response){
    var date = new Date();
    var dateString = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.end('<b>Hello World</b><br /><i>The date is: ' + dateString + '</i><br /><br />The requested URL is: ' + request.url);    
}).listen(3000);

This code is all that is required to start a Node.js server and start listening on a port on the system for requests. The above code listens on port 3000 and responds with the static HTML passed in the response.send method to the client browser. As the response is not specific to any URL, the same response would be sent for all requests.

The module http is installed globally and is available to any Node.js module on the system. The first statement gets a reference of the object returned by this module. The HTTP module is the low-level API to create a Node.js server.

To run this application, open a command prompt and move to the folder containing this file. Now run the following command:

> node server.js

Start a browser and change the URL to: http://localhost:3000. The output on the page would be similar to the following:

nodejs-hello-world

Conclusion

You just got started with Node.js. Hope this article covers all the necessary things that one needs to know to get started with Node.js.

We will cover more features of Node.js in upcoming articles. Stay tuned!

Tutorial 2: Node.js Serving HTML pages and Static content

Tutorial 3: Using Node.js to build REST APIs

Tutorial 4: Node.js Modules System

Tutorial 5: Node.js: Understanding NPM

Tutorial 6: Using Underscore.js in Node.js apps

Tutorial 7: Connecting to MongoDB from Node.js using MongoDB driver

Tutorial 8: Connecting to MongoDB using Mongoose

Articles by other DotNetCurry Authors

Tutorial 9: Create a Web Server using Node.js

Tutorial  10: Read a CSV file using Node.js

Tutorial 11: Using the DNS module in Node.js

Tutorial 12: Using Node.js to Write data to a CSV file

Tutorial 13: Upload Files using Node.js

Tutorial 14: Process Data over HTTP in Node.js

Tutorial 15: Using Promises in Node.js Applications

Tutorial 16: Unit testing Node.js Applications using Mocha

Tutorial 17: Implement Data Serialization using Node.js for JSON Data

Tutorial 18: Create a WebSocket Server Using Node.js

Tutorial 19: Calling Externally Hosted Service using Node.js

Tutorial 20: Basic Authentication in Node.js

Tutorial 21: Digest Authentication using Node.js

Tutorial 22: Debugging Node.js applications using Node Inspector

Tutorial 23: Connect to SQL Server using Node.js and mssql package 

Tutorial 24: Promises in Node.js using Q - Farewell to Callbacks

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Rabi Kiran (a.k.a. Ravi Kiran) is a developer working on Microsoft Technologies at Hyderabad. These days, he is spending his time on JavaScript frameworks like AngularJS, latest updates to JavaScript in ES6 and ES7, Web Components, Node.js and also on several Microsoft technologies including ASP.NET 5, SignalR and C#. He is an active blogger, an author at SitePoint and at DotNetCurry. He is rewarded with Microsoft MVP (Visual Studio and Dev Tools) and DZone MVB awards for his contribution to the community


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook