Learn Node.js in 8 hours [For Beginners]

Written by ontoborn | Published 2017/04/22
Tech Story Tags: hire-nodejs-developers | javascript | nodejs | node

TLDRvia the TL;DR App

Node.js is a very powerful JavaScript-based framework/platform built on Google Chrome’s JavaScript V8 Engine. Node is also used to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications. Node.js is also open source, completely free, and used by thousands of developers around the world.

Why use Node.js?

We will have a look into the real worth of Node.js in the coming chapters, but what is it that makes this framework so famous. Over the years, most of the applications were based on a stateless request-response framework. In these sort of applications, it is up to the developer to ensure the right code was put in place to ensure the state of web session was maintained while the user was working with the system.

But with Node.js web applications, you can now work in real-time and have a 2-way communication. The state is maintained, and the either the client or server can start the communication.

Features of Node.js

  1. Node uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which makes the runtime engine much faster and hence processing of requests within Node also become faster.
  2. Handling of concurrent requests — Another key functionality of Node is the ability to handle concurrent connections with a very minimal overhead on a single process.
  3. The Node.js library used JavaScript — This is another important aspect of development in Node.js. A major part of the development community are already well versed in javascript, and hence, development in Node.js becomes easier for a developer who knows javascript.
  4. There are an Active and vibrant community for the Node.js framework. Because of the active community, there are always keys updates made available to the framework. This helps to keep the framework always up-to-date with the latest trends in web development

Who uses Node.js

Node.js is used by a variety of large companies. Below is a list of a few of them.

  • Paypal — A lot of sites within Paypal have also started the transition onto Node.js.
  • LinkedIn — LinkedIn is using Node.js to power their Mobile Servers, which powers the iPhone, Android, and also Mobile Web products.
  • Mozilla has implemented Node.js to support browser APIs which has half a billion installs.
  • Ebay hosts their HTTP API service in Node.js

When to Use Node.js

Node.js is best for usage in streaming or event-based real-time applications like

  1. Chat applications
  2. Game servers — Fast and high-performance servers that need to processes thousands of requests at a time, then this is an ideal framework.
  3. Good for collaborative environment — This is good for environments which manage document. In document management environment you will have multiple people who post their documents and do constant changes by checking out and checking in documents. So Node.js is good for these environments because the event loop in Node.js can be triggered whenever documents are changed in a document managed environment.
  4. Advertisement servers — Again here you could have thousands of request to pull advertisements from the central server and Node.js can be an ideal framework to handle this.
  5. Streaming servers — Another ideal scenario to use Node is for multimedia streaming servers wherein clients have request’s to pull different multimedia contents from this server.

Traditional Web Server Model:

In the traditional web server model, each request is handled by a dedicated thread from the thread pool. If no thread is available in the thread pool at any point of time then the request waits till the next available thread. Dedicated thread executes a particular request and does not return to thread pool until it completes the execution and returns a response

Node.js Process Model:

Node processes user requests differently when compared to a traditional web server model. Node runs in a single process and the application code runs in a single thread and thereby needs less resources than other platforms. All the user requests to your web application will be handled by a single thread and all the I/O work or long running job is performed asynchronously for a particular request. So, this single thread doesn’t have to wait for the request to complete and is free to handle the next request. When asynchronous I/O work completes then it processes the request further and sends the response.

An event loop is constantly watching for the events to be raised for an asynchronous job and executing callback function when the job completes. Internally, Node.js uses libev for the event loop which in turn uses internal C++ thread pool to provide asynchronous I/O.

Setup Node.js Development Environment:

In this section, you will learn about the tools required and steps to setup development environment to develop a Node.js application.

Node.js development environment can be setup in Windows, Mac, Linux and Solaris. The following tools/SDK are required for developing a Node.js application on any platform.

  1. Node.js
  2. Node Package Manager (NPM)
  3. IDE (Integrated Development Environment) or TextEditor

NPM (Node Package Manager) is included in Node.js installation since Node version 0.6.0., so there is no need to install it separately.

Install Node.js on Windows:

Visit Node.js official web site https://nodejs.org. It will automatically detect OS and display download link as per your Operating System. For example, it will display following download link for 64 bit Windows OS.

After you download the MSI, double-click on it to start the installation as shown below.

Click Next to read and accept the License Agreement and then click Install. It will install Node.js quickly on your computer. Finally, click finish to complete the installation.

Verify Installation:

Once you install Node.js on your computer, you can verify it by opening the command prompt and typing node — version. If Node.js is installed successfully then it will display the version of the Node.js installed on your machine, as shown below.

IDE:

Node.js application uses JavaScript to develop an application. So, you can use any IDE or texteditor tool that supports JavaScript syntax. However, an IDE that supports auto complete features for Node.js API is recommended e.g. Visual Studio, Sublime text, Eclipse, Aptana etc.

Learn how to setup MS Visual Studio for Node.js development in the next section.

Node.js Console:

Node.js comes with virtual environment called REPL (aka Node shell). REPL stands for Read-Eval-Print-Loop. It is a quick and also easy way to test simple Node.js/JavaScript code.

To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node as shown below. It will change the prompt to > in Windows and MAC.

You can now test pretty much any Node.js/JavaScript expression in REPL. For example, if your write “10 + 20” then it will display result 30 immediately in new line.

> 10 + 20

30

The + operator also concatenates strings as in browser’s JavaScript.

> “Hello” + “World”

Hello World

You can also define variables and perform some operation on them.

> var x = 10, y = 20;

> x + y

30

If you need to write multi line JavaScript expression or function then just press Enter whenever you want to write something in the next line as a continuation of your code. The REPL terminal will display three dots (…), it means you can continue on next line. Write .break to get out of continuity mode.

For example, you can define a function and execute it as shown below.

You can execute an external JavaScript file by writing node fileName command. For example, assume that node-example.js is on C drive of your PC with following code.

node-example.js

console.log(“Hello World”);

Now, you can execute node-exampel.js from command prompt as shown below.

Run External JavaScript file

To exit from the REPL terminal, press Ctrl + C twice or write .exit and press Enter.

Thus, you can execute any Node.js/JavaScript code in the node shell (REPL). This will give you a result which is similar to the one you will get in the console of Google Chrome browser.

The following table lists important REPL commands.

REPL CommandDescription.helpDisplay help on all the commandstab KeysDisplay the list of all commands.Up/Down KeysSee previous commands applied in REPL..save filenameSave current Node REPL session to a file..load filenameLoad the specified file in the current Node REPL session.ctrl + cTerminate the current command.ctrl + c (twice)Exit from the REPL.ctrl + dExit from the REPL..breakExit from multiline expression..clearExit from multiline expression.

Node.js Module:

Module in Node.js is a simple or complex functionality organized in single and also multiple JavaScript files which can be reused throughout the Node.js application.

Each module in Node.js has its own context, so it cannot interfere with other modules or pollute global scope. Also, each module can be placed in a separate .js file under a separate folder.

Node.js implements CommonJS modules standard. CommonJS is a group of volunteers who define JavaScript standards for web server, desktop, and console application.

Module Types:

Node.js includes three types of modules:

  1. Core Modules
  2. Local Modules
  3. Third Party Modules

Node.js Core Modules:

Node.js is a light weight framework. The core modules include bare minimum functionalities of Node.js. These core modules are compiled into its binary distribution and load automatically when Node.js process starts. However, you need to import the core module first in order to use it in your application.

The following table lists some of the important core modules in Node.js.

Core ModuleDescriptionhttphttp module includes classes, methods and events to create Node.js http server.urlurl module includes methods for URL resolution and parsing.querystringquerystring module includes methods to deal with query string.pathpath module includes methods to deal with file paths.fsfs module includes classes, methods, and events to work with file I/O.utilutil module includes utility functions useful for programmers.

Loading Core Modules:

In order to use Node.js core or NPM modules, you first need to import it using require() function as shown below.

var module = require(‘module_name’);

As per above syntax, specify the module name in the require() function. The require() function will return an object, function, property and also any other JavaScript type, depending on what the specified module returns.

The following example demonstrates how to use Node.js http module to create a web server.

Example: Load and Use Core http Module

var http = require(‘http’); var server = http.createServer(function(req, res){ //write code here }); server.listen(5000);

In the above example, require() function returns an object because http module returns its functionality as an object, you can then use its properties and methods using dot notation e.g. http.createServer().

Node.js Local Module:

Local modules are modules created locally in your Node.js application. These modules include different functionalities of your application in separate files and folders. You can also package it and distribute it via NPM, so that Node.js community can use it. For example, if you need to connect to MongoDB and fetch data then you can create a module for it, which can be reused in your application.

Writing Simple Module:

Let’s write simple logging module which logs the information, warning or error to the console.

In Node.js, module should be placed in a separate JavaScript file. So, create a Log.js file and write the following code in it.

In the above example of logging module, we have created an object with three functions — info(), warning() and error(). At the end, we have assigned this object to module.exports. The module.exports in the above example exposes a log object as a module.

The module.exports is a special object which is included in every JS file in the Node.js application by default. Use module.exports or exports to expose a function, object and also variable as a module in Node.js.

Now, let’s see how to use the above logging module in our application.

Loading Local Module:

To use local modules in your application, you need to load it using require() function in the same way as core module. However, you need to specify the path of JavaScript file of the module.

The following example demonstrates how to use the above logging module contained in Log.js.

In the above example, app.js is using log module. First, it loads the logging module using require() function and specified path where logging module is stored. Logging module is contained in Log.js file in the root folder. So, we have specified the path ‘./Log.js’ in the require() function. The ‘.’ denotes a root folder.

The require() function returns a log object because logging module exposes an object in Log.js using module.exports. So now you can use logging module as an object and call any of its function using dot notation e.g myLogModule.info() or myLogModule.warning() or myLogModule.error()

Run the above example using command prompt (in Windows) as shown below.

Thus, you can create a local module using module.exports and use it in your application.

Let’s see how to expose different types as a node module using module.exports in the next section.

module.exports:

In the previous section, you learned how to write a local module using module.exports. In this section, you will learn how to expose different types as a module using module.exports.

The module.exports or exports is a special object which is included in every JS file in the Node.js application by default. module is a variable that represents current module and exports is an object that will be exposed as a module. So, whatever you assign to module.exports or exports, will be exposed as a module.

Let’s see how to expose different types as a module using module.exports.

Export Literals:

As mentioned above, exports is an object. So it exposes whatever you assigned to it as a module. For example, if you assign a string literal then it will expose that string literal as a module.

The following example exposes simple string message as a module in Message.js.

Now, import this message module and use it as shown below.

Run the above example and see the result as shown below.

Export Object:

exports is an object. So, you can attach properties or methods to it. The following example exposes an object with a string property in Message.js file.

In the above example, we have attached a property “SimpleMessage” to the exports object. Now, import and use this module as shown below.

In the above example, require() function will return an object { SimpleMessage : ‘Hello World’} and assign it to the msg variable. So, now you can use msg.SimpleMessage.

Run the above example by writing node app.js in the command prompt and see the output as shown below.

Node.js Web Server:

In this section, we will learn how to create a simple Node.js web server and handle HTTP requests.

To access web pages of any web application, you need a web server. The web server will handle all the http requests for the web application e.g IIS is a web server for ASP.NET web applications and Apache is a web server for PHP or Java web applications.

Node.js provides capabilities to create your own web server which will handle HTTP requests asynchronously. You can use IIS or Apache to run Node.js web application but it is recommended to use Node.js web server.

Create Node.js Web Server:

Node.js makes it easy to create a simple web server that processes incoming requests asynchronously.

The following example is a simple Node.js web server contained in server.js file.

In the above example, we import the http module using require() function. The http module is a core module of Node.js, so no need to install it using NPM. The next step is to call createServer() method of http and specify callback function with request and response parameter.

Run the above web server by writing node server.js command in command prompt or terminal window and it will display message as shown below.

This is how you create a Node.js web server using simple steps. Now, let’s see how to handle HTTP request and send response in Node.js web server.

References

Tutorial Teacher

Hire NodeJS Developers

You can hire Nodejs developers at an hourly, weekly or monthly basis at http://ontoborn.com


Written by ontoborn | We are a software engineering startup. We help non tech startup entrepreneurs build their software products
Published by HackerNoon on 2017/04/22