Node Js Sample Code

Posted on  by admin

This Node js tutorial is designed for beginners to help you learn Node.js step by step. All you need to do is follow this Node.js tutorial stepwise.

Each step covers important topics related to Node.js. This Node.js tutorial is divided into 7 steps. We expect you to follow this step by step. We are going to cover the following topics in this Node.js tutorial:.

Step 1: Node js basic concepts – Libuv, Event loop, Libev. Step 2: Building a Simple Web Server in Node.js. Step 3: Node.js modules and NPM. Step 4: File system module. Step 5: Express framework. Step 6: Databases – MySQL, MongoDB, PostgreSQL and Redis.

Step 7: Deployment – deploying applications in Digitalocean Server. After reading this Node.js tutorial, you should be able to build applications using Node.js and deploy it on a cloud server.

Node.js runs on top of V8—Chrome runtime engine—that compiles the JavaScript code in the native machine code (one of the reasons why Google Chrome runs fast and consumes a lot of memory), followed by the custom C++ code.

The original version has 8,000 lines of code (LOC)—and then, the standard libraries for programmers. The following is the figure of Node.js architecture:. The V8 JavaScript engine is an open-source JavaScript engine developed for the Chrome project. The innovation behind V8 is that it compiles the JavaScript code in native machine code and executes it.

Step 6: Databases – MySQL, MongoDB, PostgreSQL and Redis.

The developers of V8 used the just-in-time (JIT) compiler methodology to improve the code compilation time.

It is open-source and is used in the Node.js and MongoDB project.

Link: https://github.com/v8/v8. The libuv library is a cross-platform library that provides an asynchronous I/O facility by enabling an event-driven I/O operation.

The libuv library creates a thread for the I/O operation (file, DNS, HTTP, and so on) and returns a callback.

Upon completion of the particular I/O operation, it returns the events so that the callee program does not have to wait for the completion of the I/O operation.

As I mentioned earlier, libuv assigns threads for the I/O operation and returns the callback to the callee program. Therefore, Node.js internally creates threads for I/O operation; however, it gives the programmer access to a single runtime thread.

In this way, things are simple and sweet:. When you make an HTTP request to the web server built using Node.

It creates the libuv thread and is ready to accept another request. As soon as the events are triggered by libuv, it returns the response to the user.

The libuv library provides the following important core features:. Fully featured event loop. Asynchronous filesystem operations. Thread and synchronization primitives. Asynchronous TCP and UDP sockets. Signal handling. The libuv library internally uses another famous library called libeio, which is designed for threading and asynchronous I/O events and libev, which is a high-performance event loop.

Therefore, you can treat libuv as a package wrapper for both of them. Let’s learn a little bit about multi-threading and single threading.

Step 3: Node modules and NPM

The multi-threading approach provides parallelism using threads so that multiple programs can simultaneously run.

it is really difficult to handle concurrency and deadlock in a multi-threading system.

Download this tutorial in a PDF format

On the other hand, with single-threading, there is no chance of deadlock in the process, and managing the code is also easy. You can still hack and busy the event loop for no reason; however, that’s not the point.

Consider the following working diagram that is developed by StrongLoop—one of the core maintainers of Node.js:. Node.js uses single-threading for runtime environment; however, internally, it does create multiple threads for various I/O operations.

It doesn’t imply that it creates threads for each connection, libuv contains the Portable Operating System Interface (POSIX) system calls for some I/O operations.

Skipping hello world

Multi-threading blocks the I/O until the particular thread completes its operation and results in overall slower performance.

Consider the following image:. If the single-threading programs work correctly, they will never block the I/O and will be always ready to accept new connections and process them.

As you can see in the image earlier, I/O does not get blocked by any thread in Node.js.

Then, how does it notify particular processes that the task has been done or an error has occurred? Node.js is asynchronous in nature and you need to program it in an asynchronous way, which you cannot do unless you have a clear understanding of the event loop.

If you know how the event loop works, you will no longer get confused and hopefully, never block the event loop.

The Node.js runtime system has an execution stack, where it pushes every task to execute. The operating system pops the task from the execution stack and conducts the necessary action required to run the task.

Step 4: File system module.

To run the asynchronous code, this approach won’t work. The libuv library introduces a queue that stores the callback for each asynchronous operation. Event loop runs on a specific interval, which is called tick in the Node.js terminology and checks the stack.

If the stack is empty, it takes the callback from the queue and pushes it in the stack for execution, as shown in the following figure:. The libuv library creates the thread and returns the callback to us.

As it’s an asynchronous operation, it goes to the queue instead of the stack and the event loop fetches it when the stack is empty and does the execution.

You can validate the same concept using the setTimeout() function. Consider the following code:. console.log('i am first');setTimeout(timeout()=>{ console.log('i am second');},5000);console.log('i am third');.

If you run this code, you will get an output similar to the following:. The reason is obvious, setTimeout() waits for five seconds and prints its output; however, that does not block the event loop.

Let’s set the timer to 0 seconds and see what happens:. console.log('i am first');setTimeout(timeout()=>{ console.log('i am second');},0);console.log('i am third');.

The output is still the same:. Even if you set the timer to 0, it goes in the queue; however, it is immediately processed as its time is 0 second.

The event loop recognizes that the stack is still not empty, that is, the third console was in process; therefore, it pushes the callback after the next tick of the event loop. We have covered the basics of Node. Let’s proceed ahead with the installation in your operating system.

If you already have Node installed, kindly skip this section.

To install Node in Windows Operating System, follow these steps:. Step 1: Download the Installer.

Step 7: Deploying Node application to a Cloud Server

Download the Node installer from the official site. Step 2: Run the installer. Run the installer and click Next until the setup wizard is complete.

Step 3: Verify the installation.

Open command prompt or PowerShell and run the following command. It should return the node version. Step 4: Update the NPM. To install Node in the Mac operating system, follow these steps:. Step 1: Download the Installer.

Download the Node installer from the official site. Step 2: Run the installer. Run the installer and click Continue until the setup wizard is complete. Step 3: Verify the installation. Open the terminal and run the following command.

It should return the node version. Step 4: Update the NPM using the following command. To install Node in the Ubuntu operating system, open the terminal and run the following command one by one. curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -. Also, install the build tools. Verify the installation, run the following command. It should return the version of Node installed in your system.

In our case, it is V12. Alright, let’s move to the next step. Let’s build a simple Web application that returns a message as “Hello World” when user request the server. We will use the native HTTP module of Node to achieve the Web Server functionality. Here is the code:. const http = require('http');const hostname ='localhost';const port =3000;const server = http.createServer((req, res)=>{ res.statusCode=200; res.setHeader('Content-Type','text/plain'); res.end('Hello World ');});server.listen(port, hostname,()=>{ console.log(`Server running at http://${hostname}:${port}/`); });.

Copy/paste it in a new file. Name the file as hello.js and save it. To run this code, open your terminal and switch to the location where you have stored the file. Run this command to execute your code. You should have the following message on the terminal. Open your browser and type localhost:3000 and hit enter.

Step 2: Building a Simple Web Server in Node.js

You should see the following message. You have just developed your first Node program. Our server responds to a simple message as a text, however, in practice we need to handle different types of responses. Let’s look over some of the common response types. One of the most common responses that you need to handle while developing a Node application is JSON. Here is how you can send JSON responses. const http = require("http");const hostname ="localhost";const port =3000;const server = http.createServer((req, res)=>{ res.statusCode=200; res.setHeader("Content-Type","application/json"); res.end('{ "message" : "Hello World " }');});server.listen(port, hostname,()=>{ console.log(`Server running at http://${hostname}:${port}/`);});.

If you run this code, and navigate to the browser, you should see the following response. Let’s look over how to send HTML as a response. const port =3000;. const server = http.createServer((req, res)=>{. server.listen(port, hostname,()=>{. When you run this code, you should see the following response. Let’s go ahead and create different routes to support multiple responses. Check out the code shown below.

Step 1: Node js basic concepts

const http = require("http");const hostname ="localhost";const port =3000;const server = http.createServer((req, res)=>{ res.statusCode=200; res.setHeader("Content-Type","text/html");switch(req.url){case"/home": res.writeHead(200); res.end("");break;case"/about": res.writeHead(200); res.end("");break;default:break;}});server.listen(port, hostname,()=>{ console.log(`Server running at http://${hostname}:${port}/`);});.

Node.js Examples

As you can see, we are using switch cases to determine different routes and on each route, we are sending different responses to each route.

  • Navigate your browser to localhost:3000/home to view the response.
  • Navigate your browser to localhost:3000/about to view the second response.
  • We built a simple web server in Node. Let’s jump to the next step. Node modules are the basic building block of the Node program.
  • The node module is a set of functions that can be reused in your application.
  • Node has built-in modules as well as you can create your node modules.
  • Some of the famous built-in node modules are fs, net, http, and many of the popular modules such as express, nodemailer built on top of these built-in modules.