What is NodeJS?

28/12/2020

In this tutorial, we will get started with Node.js. Learn about some of its most popular features and will try to motivate the readers to adopt this wonderful technology for their future projects. As a prerequisite, you just need to have a passing familiarity with JavaScript and generic programming concepts, such as variables, data types and functions.

JavaScript has a strange history. It started off as a light-weight scripting language for web browsers and was treated more like a ‘toy’ than a serious programming language. But it has long since outgrown its humble beginning.

People started extending its capabilities when Google open-sourced Chrome’s JavaScript interpreter — The V8 engine. Node.js takes this JavaScript engine and extends it to work outside the realm of the browser. Node.js binds JavaScript with your operating system’s API so it can run natively on the server (or in case of a developer, on his/her desktop). Yes, this means you can implement server-side applications, desktop applications and back-end mechanisms by learning just one language — JavaScript.

Simply put, you can write .js files which contains programs written in JavaScript syntax that will get interpreted by Node.js much the same way as .py files with valid syntax are interpreted/executed by python interpreter.

There’s more to it than just knowing the language, however, Node.js has unfamiliar modules and concepts that would require patience in an unending cycle of learning new concepts. It has its own package manager (npm), version manager (nvm) and the world largest package registry. Rest assured, the initial difficulty will make your life a lot easier over the long run.

Installation

Currently there are two options for Node.js versions which you might want to consider.

  • Version 8.11.1 LTS (Recommended for most users)
  • Version 10.0.0 Current (Offers latest set of features, but not meant for production grade applications)

We will be sticking with the LTS version. Downloading Node from the official site for your operating system would also install the Node Package Manager (npm). It is difficult to talk about Node.js without getting into npm. We will come back to the package manager later on. If you are using Ubuntu or any other debian distro simply use:

$ sudo apt install nodejs

For all the binaries and the source code visit the official download page.

That’s it with installation, time to say, “Hello, World!”

Hello, World! And Creating a Server

As promised, we will be creating a hello.js file and run it using Node. In a plain text file, called hello.js, we write the following line:

console.log(“Hello, World!);

Now save the file and open a terminal in the same directory as that file and run the following command:

$node hello.js
#Or you may run
$node hello

This will give you the desired output of “Hello, World”. Just like vanilla JavaScript. But surely, we can do better…

Unlike PHP based applications which require Apache or Nginx or some other web server program to run atop, in node we write our own http routes, configure the ports and hostnames and process HTTP requests to give appropriate responses.

Sounds like a lot of work, but it is only an initial hurdle in the learning curve, and once you get a hang of things, you will be able to understand web applications in greater  depths than ever before. Let’s create a web server which listens on port 3000 on localhost and returns a text file as a response. Create a file app.js with the following contents:

const http = require(‘http’);
const hostname = ‘127.0.0.1’;
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader(‘Content-Type’, ‘text/plain’);
res.end(‘Hello Worldn);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

Before we get into the details of the code, save this file and open a terminal in the same directory as the file, then run:

$ node app

This will execute the contents of app.js file and you will get an output as follows:

Open a web browser and visit http://localhost:3000/ or http://127.0.0.1:3000/ to see a simple Hello World text on your browser window.

So what did we just do? Well, if you are familiar with JavaScript, you can probably make sense of some of it..

The first line imports the http module, which is an in-built module that comes along with Node, and it helps us listen on web sockets for requests, process http requests, and give appropriate responses.

The second and third line sets the hostname to ‘127.0.0.1’ and port  to 3000. This means we can keep reusing the variable hostname and port, instead of typing out the entire IP address. Later on, when you are actually deploying it on a server, you will replace it with the server’s IP address and a port number like 80 or 443 if it is a web server. The keyword const ensures that the variable cannot be changed elsewhere in the program.

The lines four to eight  creates a server object which takes request as req and gives response as res.

The response has a statusCode attribute to it, the res.statusCode which is set to 200 which the client interprets as “Okay” status. Error codes are 400s and 500s, for example, Error 404 is code for resource not found. Similarly, the setHeader attribute is set to ‘text/plain’ which means that the client will receive plain text. You can set this to HTML and your browser will render any valid html that the server responds with. And the end attribute is simply the text that we want to return. Instead of having a string here, real-world applications will have a static HTML file or another .js file for the client browser, which would constitute a much more useful response.

Finally, the last three lines starts the server and prints a message saying that it is active on a specific hostname and port number as set by const statements, initially. Everytime a new request comes in at the specified hostname:port combination server gives responds with appropriate response object.

What it implies?

You don’t need to understand the above code in its entirety to know the implications. We already have JavaScript on the front-end thanks to awesome frameworks like Angular and React. Along with that, we also have back-end functionalities baked into the Node.js ethos.

Web frameworks like Express.js can help you write even more complex application on top of Node.js. Fetching data from Database, creating APIs, and the front-end UI all can be written using one language.

The Power of V8

Despite all of it being a single language, there’s still a lot to learn. Different frameworks and modules have different functionalities. There are a tonne of versions to keep track of. So is there any other benefit of using the Node.js ecosystem.

One of the most important argument in support of it is that the V8 engine has an excellent support for asynchronous, non-blocking I/O. Which basically means that it a single process running on your system memory can handle multiple incoming requests What it roughly means is that if one request is being processed, and another request comes in, Node has the capability to start processing the new request even if the first request is not yet finished.

Moreover, a single process running in your memory is responsible for handling all the incoming request. Unlike PHP based applications which spawns a new process for every new incoming request.

Hopefully, this intro was enough to get you motivated about Node.js. Let’s know if you want more in-depth tutorials on similar topics by following us on Twitter, Facebook and YouTube.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Node.js Send E-Mail with Attachment

Node.js is the server side JavaScript engine that is loved by web developers and system administrators all over the world....
29/12/2020

PostgreSQL NodeJS Tutorial

Using PostgreSQL from Node.js PostgreSQL is a very popular open source database. It is widely used for almost all types...
28/12/2020

How to Update NPM Packages

Updating npm packages in Ubuntu 16.04 Node Package Manager, or npm, gets installed along with Node.js and you can use it...
28/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

SỰ KHÁC BIỆT GIỮA RESIDENTIAL PROXY VÀ PROXY DATACENTER
17/02/2024

Mua Proxy v6 US Private chạy PRE, Face, Insta, Gmail
07/01/2024

Mua shadowsocks và hướng dẫn sữ dụng trên window
05/01/2024

Tại sao Proxy Socks lại được ưa chuộng hơn Proxy HTTP?
04/01/2024

Mua thuê proxy v4 nuôi zalo chất lượng cao, kinh nghiệm tránh quét tài khoản zalo
02/01/2024