Node and Node.js


Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.



What is Node.js?

Posted in Node, Node.js
What is Node.js cover image

What is Node.js?

For a long time ,the primary usage of JavaScript was client-side scripting. This took place in the <script> tags, which is interpreted by the web browser. It was a serious limitation for developers,  as they would have to work on several languages and frameworks for both the client-side and server-side areas of a web application. 

Launched in 2009, Node.js focused on bringing JavaScript to server-side applications. There are several features that Node is well-known for, and it is primarily used to build fast and scalable network applications. With this, developers were unshackled and had much more freedom in operation. 

Here we’ll answer such questions as what Node.js is, how it works and where it is used, among other things.

What is Node.js?

Node is known as an open-source server-side scripting language. It is a run-time environment that lets you execute JavaScript outside of a browser. With it, JavaScript finds utility outside of just being used for making websites more interactive. Built on Google Chrome’s V8 JS Engine, it is free of cost and has strong community support.

It is important to understand that Node.js is neither a library nor a framework. Rather it is a cross-platform runtime environment (RTE) used to run several web applications. The RTE has web APIs to build code and a JS engine to parse it. As such, Node.js is lightweight and easily deployable. 

What does Node.js Do?

Node.js helps in the building of real-time web applications, specifically highly scalable server-side applications The RTE is event driven, asynchronous and cross-platform, which provide several benefits to developers.

Whereas before Node.js, it would be the client initiating communication, now it is possible for both the client and server to initiate communication. This gives developers the ability to build real-time websites with significantly enhanced capabilities. 

Is Node.Js Frontend or Backend?

Node.js can be used in both frontend and backend applications. Examples of frontend applications are code processors and packages which are a collection of several components, put together as one using Node. Backend examples include API calls, database integration and real-time applications.

Where is Node.js Used?

Node.js is used everywhere from up and coming startups to the biggest tech companies in the world. These companies include Netflix, Twitter, Trello, eBay, Walmart, LinkedIn, PayPal and Alibaba. The Node.js purpose is varied, but a large part of it comes down to offering event-driven, asynchronous, and fast communications.

To give you some more context, Node.js was used to build Netflix’s UI and improve the loading times of the startup sequence, as well as improve LinkedIn’s mobile app experience after the latter moved from Ruby on Rails to Node.

Features of Node.js

Node.js has several features, which is why it has become such a critical part of so many companies and teams. Here they are summarized: 

  • Event driven: Node.js allows event-driven programming through a module. This lets a particular function execute upon a specific event. Events in Node,js helps the server get a response from a previous API call.
  • Asynchronous: By being asynchronous, servers handle requests in a single thread, processes, sends a response back, and moves on to the next response. All Node.js API libraries are asynchronous. 
  • Extremely fast: Node.js is built on Google Chrome’s V8 JavaScript engine. This engine is well suited for web app development and is helpful for machine language-based products and servers
  • Cross-platform RTE: It is compatible with a range of platforms, including Windows, macOS, Linux, UNIX, and several mobile platforms
  • Microservice development and quick deployment: Node.js has the ability to deploy and develop web development apps rapidly. It also assists in the development of microservices as Node.js can process data quickly.
  • Scalability: Node.js, is suitable for high scalability. It handles the concurrent requests and manages the load balance of CPU cores. Interestingly, it splits the software horizontally that in turn helps the organizations to showcase the app on various systems, targeting large groups of audiences. 
  • Open-source community: Node.js has an extensive global community. The developers can find strong support from community members, who also make packages, tools, modules, frameworks, available to the developers free of cost.
  • Fast data streaming: Node.js offers greater video streaming speed

How Does Node.js Work?

To understand how Node.js works, we should take a look at the Node Architecture. Node depends on many libraries, with two major dependencies of node operations being V8 and LIBUV. 

We’ll go over both. 

V8

Node.js is built on Google’s V8 engine. It is known to be the fastest JavaScript engine. It helps convert JavaScript code into machine code. The generated result is returned to Node.js. 

LIBUV

LIBUV is an open-source library that relies on asynchronous I/O and implements thread pool and event loop.

Asynchronous I/O helps applications overlap I/O operations. This is also called non-blocking. On the other hand, in synchronous I/O, the thread has to wait till the operation finishes, as opposed to asynchronous I/O, where it does not wait. 

Event loop

Node.js runs processes in a single thread, and a thread is a set of instructions. In PHP, every task runs in separate threads.

For instance, in Node, which is single-threaded, 3 separate tasks would execute all in one  thread. This event loop is the core of node.js. It executes the callback functions in a single thread. 

It also manages tasks and balances heavy ones by offloading them in the thread pool and tackles the lighter tasks by itself. 

Thread pool

There are 4 additional threads entirely separate from the main thread. There is a certain amount of liberty to configure these, from 4 to 128 threads, but 4 threads should suffice for your work. Together, these four are termed as the Thread pool.

Now, there are various heavy tasks such as cryptography, DNS lookups, password caching, etc. Such tasks could create a bottleneck in the main thread. Node offloads them into the thread pool.

Important Libraries

Besides the event loop and thread pool, there are a few other essential libraries in Node. These are:

  • OpenSSL for cryptography
  • C-ARES for DNS queries 
  • HTTP parser
  • Zlib

Event-Driven Architecture

Most of the tasks executed in Node are based on events. The interaction takes place with some observers listening to the objects or an emitter object. Most events originate from files, processes, or interactions with networks. 

Each event in an emitter consists of a method ON that has at least two arguments namely:

  • Name of the event
  • Listener function

Consider this snippet of node server:

const net = require("net");

 

const server = net.createServer().listen(8081, "127.0.0.1");

 

server.on("listening", function () {

  console.log("Server listening!");

});

 

server.on("connection", function (socket) {

  console.log("Client connected!");

  socket.end("Hello client!");

});

In this bit of code, a server listening on port 8081 has been created. To register two listener functions, the ON method is called on the server object. When the server starts, the listening event is fired. Whereas, the connection event fires after the client connects to 127.0.0.1:8081. 

Here, the event emitter is the server or the subject. On the other hand, list enter functions are the observers. To understand this better, let’s look at the EventEmitter. 

The root class in the event-driven module in Node.js is called the EventEmitter. 

It has two main functions, namely on and emit. If you wish to listen to the events, you can call addEventListener on the subject. Call the events in your browser as shown in the below-mentioned code:

const btn = document.getElementById('subscribe');

 

btn.addEventListener("click", function () {

    console.log("Button clicked");

});

Now, in the same way, we use on. Here is a snippet of code:

server.on("listening", () => {

  console.log("Server listening!");

});

Let’s move on to how to use Node.

How to Use Node

To begin, you will first have to download and install Node.js on your operating system. In order to run JavaScript files in Node, you must save follow the command written below in a file called script.js:

console.log('Example of Node’);

After you run the terminal command, the node script.js in the same script.js folder as mentioned above, and it initiates Node. 

Additionally, when it comes to sharing modules between several Node developers, Node packages offer convenience. Npm is the default package manager for Node. It grants access to thousands of open-source packages. 

Node as a REPL

REPL or Read Evaluate-Print-Loop Functionality helps in the execution of JS commands from the command line. In the case of node, you can run the node command in the terminal and press enter to launch the REPL. 

Now, you can run any JavaScript code and Node will print the result for you. 

Take a look at the this example to understand it more clearly:

$ node

> 4 + 5

9

> function nodeIsGreat() {

... console.log('Node is great!');

... }

undefined

> nodeIsGreat()

Node is great!

undefined

> .exit

$

As you can see in line 4, the function nodeIsGreat is defined. This function takes in multiple lines, hence, Node REPL prints at the beginning that reads the input statement by the user.

If you wish to exit the Node REPL, you can use the .exit command whenever you want to. You can also press ctrl + c. twice to exit. 

How to Load Existing Files

It is possible for Node REPL to load existing JS files. Just save the code in script.js as shown below:

var z = ‘Node programming’

You can also use .load to take the path argument to load it into REPL. To do that, use the following mentioned command:

.load ./script.js

 

$ node

> .load ./script.js

var z = 'Node Programming!';

 

> a

Once the script file loads, you can easily access the variables in the REPL. Hence, the value of the z variable is set by the script.js and thereby it prints the text, ‘Node Programming’, and displays it on the screen.

Advantages and Disadvantages of Node.js

While it is extremely useful, Node.js does have some downsides. It’s a matter of knowing when to use Node, just as it is with some many concepts in development. Here is a quick overview of the advantages and disadvantages of Node.js.

node.js

Advantages of Node.js

  • Powerful performance for real-time applications
  • Highly scalable
  • Extensive community support
  • Facilitates cross-platform applications
  • Easy to learn
  • Shorter app response times
  • Quick caching results in faster loading times

 

Disadvantages of Node.js

  • Performance slows for CPU intensive tasks
  • Asynchronous programming can be a double-edged sword, as it results in heavy callbacks
  • The Node API frequently changes, which could create bugs and compatibility issues

Node.js Can Be Very Useful and Versatile

Node.js is a great pick to develop several applications, as it handles asynchronous data flow via multiple concurrent requests. Social networking, data streaming, or project management applications - all of these can be developed with Node.js.

Being an open-source and server-side scripting language, Node.js has become a top choice for many developers and several big organizations. The features listed above have given them the tools to speed up applications as well as reach a larger audience through different systems.

Although it contains a few drawbacks, Node.js is definitely worth giving a shot. To learn more, check out some Node.js tutorials!

 

Want to learn Node.js faster? Take this course!
Learn Node. js from Beginning Bootcamp

Related Articles:

Zoe Biehl

Zoe Biehl

Zoe is Hackr.io's Senior Editor. With more than 8 years in the tech industry, her passion is writing and editing technology content that anyone can understand. View all posts by the Author

Leave a comment

Your email will not be published
Cancel