What Is Node and When Ought to I Use It?

So that you’ve heard of Node.js, however aren’t fairly positive what it’s or the place it matches into your growth workflow. Or possibly you’ve heard folks singing Node’s praises and now you’re questioning if it’s one thing it’s good to study. Maybe you’re aware of one other back-end expertise and need to discover out what’s completely different about Node.

If that sounds such as you, then hold studying. On this article, I’ll take a beginner-friendly, high-level take a look at Node.js and its principal paradigms. I’ll study Node’s principal use instances, in addition to the present state of the Node panorama, and give you a variety of leaping off factors (for additional studying) alongside the best way.

Please observe that, all through the article, I’ll use “Node” and “Node.js” interchangeably.

What Is Node.js?

There are many definitions to be discovered on-line. Let’s check out a few the extra common ones. That is what the challenge’s residence web page has to say:

Node.js® is a JavaScript runtime constructed on Chrome’s V8 JavaScript engine.

And that is what Stack Overflow has to supply:

Node.js is an event-based, non-blocking, asynchronous I/O runtime that makes use of Google’s V8 JavaScript engine and libuv library.

Hmmm, “event-based”, “non-blocking”, “asynchronous I/O” — that’s rather a lot to digest in a single go. So let’s method this from a distinct angle and start by specializing in the opposite element that each descriptions point out — the V8 JavaScript engine.

Node Is Constructed on Google Chrome’s V8 JavaScript Engine

The V8 engine is the open-source JavaScript engine that runs in Google Chrome and different Chromium-based internet browsers, together with Courageous, Opera, and Vivaldi. It was designed with efficiency in thoughts and is chargeable for compiling JavaScript on to native machine code that your laptop can execute.

Nonetheless, once we say that Node is constructed on the V8 engine, we don’t imply that Node applications are executed in a browser. They aren’t. Slightly, the creator of Node (Ryan Dahl) took the V8 engine and enhanced it with numerous options, resembling a file system API, an HTTP library, and quite a few working system–associated utility strategies.

Which means that Node.js is a program we will use to execute JavaScript on our computer systems. In different phrases, it’s a JavaScript runtime.

How Do I Set up Node.js?

On this subsequent part, we’ll set up Node and write a few easy applications. We’ll additionally take a look at npm, a package deal supervisor that comes bundled with Node.

Node Binaries vs Model Supervisor

Many web sites will suggest that you just head to the official Node obtain web page and seize the Node binaries on your system. Whereas that works, I might counsel that you just use a model supervisor as a substitute. It is a program that lets you set up a number of variations of Node and change between them at will. There are numerous benefits to utilizing a model supervisor. For instance, it negates potential permission points when utilizing Node with npm and allows you to set a Node model on a per-project foundation.

Should you fancy going the model supervisor route, please seek the advice of our fast tip: Set up A number of Variations of Node.js utilizing nvm. In any other case, seize the right binaries on your system from the hyperlink above and set up these.

“Hi there, World!” the Node.js Approach

You possibly can examine that Node is put in in your system by opening a terminal and typing node -v. If all has gone effectively, you need to see one thing like v12.14.1 displayed. That is the present LTS model on the time of writing.

Subsequent, create a brand new file hi there.js and replica within the following code:

console.log(“Hi there, World!”);

This makes use of Node’s built-in console module to show a message in a terminal window. To run the instance, enter the next command:

node hi there.js

If Node.js is configured correctly, “Hi there, World!” will likely be displayed.

Node.js Has Glorious Assist for Fashionable JavaScript

As might be seen on this compatibility desk, Node has wonderful help for ECMAScript 2015 (ES6) and past. As you’re solely concentrating on one runtime (a particular model of the V8 engine), this implies that you could write your JavaScript utilizing the newest and most trendy syntax. It additionally implies that you don’t usually have to fret about compatibility points — as you’ll for those who have been writing JavaScript that might run in several browsers.

For instance the purpose, right here’s a second program that makes use of a number of trendy JavaScript options, resembling tagged template literals, object destructuring and Array.prototype.flatMap():

perform upcase(strings, …values)
return values.map(identify => identify[0].toUpperCase() + identify.slice(1))
.be part of(‘ ‘) + strings[2];

const particular person = ;

const first, final = particular person;
const emoticon = [ [‘┌’, ‘(‘], [‘˘’, ‘⌣’], [‘˘’, ‘)’, ‘ʃ’] ];

upcase`$ $ is the creator of JavaScript! ` + emoticon.flat().be part of(”)

Save this code to a file referred to as index.js and run it out of your terminal utilizing the command node index.js. It’s best to see Brendan Eich is the creator of JavaScript! ┌(˘⌣˘)ʃ output to the terminal.

Introducing npm, the JavaScript Package deal Supervisor

As I discussed earlier, Node comes bundled with a package deal supervisor referred to as npm. To examine which model you will have put in in your system, sort npm -v.

Along with being the package deal supervisor for JavaScript, npm can also be the world’s largest software program registry. There are over 1,000,000 packages of JavaScript code obtainable to obtain, with billions of downloads per week. Let’s take a fast take a look at how we’d use npm to put in a package deal.

Putting in a Package deal Globally

Open your terminal and sort the next:

npm set up -g jshint

This can set up the jshint package deal globally in your system. We are able to use it to lint the index.js file from the earlier instance:

jshint index.js

It’s best to now see quite a few ES6-related errors. If you wish to repair them up, add /* jshint esversion: 6 */ to the highest of the index.js file, re-run the command and linting ought to cross.

Should you’d like a refresher on linting, see A Comparability of JavaScript Linting Instruments.

Putting in a Package deal Regionally

We are able to additionally set up packages domestically to a challenge, versus globally, on our system. Create a check folder and open a terminal in that listing. Subsequent sort this:

npm init -y

This can create and auto-populate a package deal.json file in the identical folder. Subsequent, use npm to put in the lodash package deal and put it aside as a challenge dependency:

npm set up lodash –save

Create a file named check.js and add the next:

const _ = require(‘lodash’);

const arr = [0, 1, false, 2, ”, 3];

Lastly, run the script utilizing node check.js. It’s best to see [ 1, 2, 3 ] output to the terminal.

Working with the package deal.json File

Should you take a look at the contents of the check listing, you’ll discover a folder entitled node_modules. That is the place npm has saved lodash and any libraries that lodash is dependent upon. The node_modules folder shouldn’t be checked in to model management, and may, in truth, be re-created at any time by working npm set up from throughout the challenge’s root.

Should you open the package deal.json file, you’ll see lodash listed underneath the dependencies area. By specifying your challenge’s dependencies on this means, you permit any developer anyplace to clone your challenge and use npm to put in no matter packages it must run.

Should you’d like to search out out extra about npm, you should definitely learn our article A Newbie’s Information to npm — the Node Package deal Supervisor.

What Is Node.js Used For?

Now that we all know what Node and npm are and the way to set up them, we will flip our consideration to the primary of their widespread makes use of: putting in (by way of npm) and working (by way of Node) numerous construct instruments — designed to automate the method of creating a contemporary JavaScript software.

These construct instruments are available all sizes and styles, and also you gained’t get far in a contemporary JavaScript panorama with out bumping into them. They can be utilized for something from bundling your JavaScript recordsdata and dependencies into static belongings, to working checks, or computerized code linting and elegance checking.

We have now a variety of articles masking construct tooling on SitePoint. Right here’s a brief number of my favorites:

And if you wish to begin creating apps with any trendy JavaScript framework (for instance, React or Angular), you’ll be anticipated to have a working information of Node and npm (or possibly Yarn). This isn’t since you want a Node again finish to run these frameworks. You don’t. Slightly, it’s as a result of these frameworks (and lots of, many associated packages) are all obtainable by way of npm and depend on Node to create a smart growth surroundings during which they will run.

Should you’re fascinated about discovering out what function Node performs in a contemporary JavaScript app, learn The Anatomy of a Fashionable JavaScript Software.

Node.js Lets Us Run JavaScript on the Server

Subsequent we come to one of many greatest use instances for Node.js — working JavaScript on the server. This isn’t a brand new idea, and was first tried by Netscape means again in 1994. Node.js, nonetheless, is the primary implementation to achieve any actual traction, and it offers some distinctive advantages, in comparison with conventional languages. Node now performs a crucial function within the expertise stack of many high-profile firms. Let’s take a look at what these advantages are.

The Node.js Execution Mannequin

In very simplistic phrases, once you connect with a conventional server, resembling Apache, it’ll spawn a brand new thread to deal with the request. In a language resembling PHP or Ruby, any subsequent I/O operations (for instance, interacting with a database) block the execution of your code till the operation has accomplished. That’s, the server has to attend for the database lookup to finish earlier than it may transfer on to processing the end result. If new requests are available whereas that is taking place, the server will spawn new threads to take care of them. That is probably inefficient, as numerous threads may cause a system to turn out to be sluggish — and, within the worst case, for the location to go down. The commonest solution to help extra connections is so as to add extra servers.

Node.js, nonetheless, is single-threaded. It’s additionally event-driven, which implies that every little thing that occurs in Node is in response to an occasion. For instance, when a brand new request is available in (one form of occasion) the server will begin processing it. If it then encounters a blocking I/O operation, as a substitute of ready for this to finish, it’ll register a callback earlier than persevering with to course of the subsequent occasion. When the I/O operation has completed (one other form of occasion), the server will execute the callback and proceed engaged on the unique request. Below the hood, Node makes use of the libuv library to implement this asynchronous (that’s, non-blocking) conduct.

Node’s execution mannequin causes the server little or no overhead, and consequently it’s able to dealing with numerous simultaneous connections. The normal method to scaling a Node app is to clone it and have the cloned cases share the workload. Node.js even has a built-in module that can assist you implement a cloning technique on a single server.

The next picture depicts Node’s execution mannequin:

Supply: Introduction To Node.js by Prof. Christian Maderazo, James Santos

Or, for those who favor movies, try this superior speak: What the heck is the occasion loop anyway? It’s not Node-specific, however does a terrific job of explaining the idea.

Are There Any Downsides?

The truth that Node runs in a single thread does impose some limitations. For instance, blocking I/O calls ought to be prevented, CPU-intensive operations ought to be handed off to a employee thread, and errors ought to at all times be dealt with accurately for worry of crashing your complete course of.

Some builders additionally dislike the callback-based model of coding that JavaScript imposes (a lot in order that there’s even a website devoted to the horrors of writing asynchronous JavaScript). However with the arrival of native Guarantees, adopted intently by async await, circulate management in trendy JavaScript has turn out to be simpler than it ever was.

“Hi there, World!” — Server Model

Let’s have a fast take a look at a “Hi there, World!” instance HTTP server:

const http = require(‘http’);

http.createServer((request, response) => ).hear(3000);

console.log(‘Server working on http://localhost:3000’);

To run this, copy the code right into a file named hello-world-server.js and run it utilizing node hello-world-server.js. Open up a browser and navigate to http://localhost:3000 to see “Hi there, World!” displayed within the browser.

Now let’s take a look on the code.

We begin by requiring Node’s native HTTP module. We then use its createServer technique to create a brand new internet server object, to which we cross an nameless perform. This perform will likely be invoked for each new connection that’s made to the server.

The nameless perform is known as with two arguments (request and response). These comprise the request from the person and the response, which we use to ship again a 200 HTTP standing code, together with our “Hi there World!” message.

Lastly, we inform the server to hear for incoming requests on port 3000, and output a message to the terminal to tell us it’s working.

Clearly, there’s much more to creating even a easy server in Node (for instance, it’s vital to deal with errors accurately), so I’d advise you to examine the documentation or seek the advice of our tutorial for those who’d like to search out out extra.

What Type of Apps Is Node.js Suited To?

Node is especially suited to constructing functions that require some type of real-time interplay or collaboration — for instance, chat websites, or apps resembling CodeShare, the place you possibly can watch a doc being edited reside by another person. It’s additionally match for constructing APIs the place you’re dealing with a number of requests which are I/O pushed (resembling these needing to carry out operations on a database), or for websites involving information streaming, as Node makes it doable to course of recordsdata whereas they’re nonetheless being uploaded. If this real-time facet of Node is one thing you’d prefer to look into extra, try our tutorial on Constructing a Actual-time Chat App.

But saying this, not everybody goes to be constructing the subsequent Trello or the subsequent Google Docs, and actually, there’s no motive that you could’t use Node to construct a easy CRUD app. Nonetheless, for those who comply with this route, you’ll quickly discover out that Node is fairly bare-bones and that the best way you construct and construction the app is left very a lot as much as you. There are numerous frameworks you should use to scale back the boilerplate, with Categorical having established itself because the entrance runner. But even an answer resembling Categorical is minimal, which means that if you wish to do something barely out of the bizarre, you’ll want to tug in further modules from npm. That is in stark distinction to frameworks resembling Rails or Laravel, which include plenty of performance out of the field.

Should you’d like to have a look at constructing a fundamental, extra conventional app, try our tutorial Find out how to Construct and Construction a Node.js MVC Software.

What Are the Benefits of Node.js?

Apart from pace and scalability, an often-touted benefit of utilizing JavaScript on an online server — in addition to within the browser — is that your mind now not wants to modify modes. You are able to do every little thing in the identical language, which, as a developer, makes you extra productive (and hopefully, happier). For instance, you possibly can simply share code between the server and the consumer.

One other of Node’s large pluses is that it speaks JSON. JSON might be an important information trade format on the Internet, and the lingua franca for interacting with object databases (resembling MongoDB). JSON is ideally suited to consumption by a JavaScript program, which means that once you’re working with Node, information can circulate neatly between layers with out the necessity for reformatting. You possibly can have one syntax from browser to server to database.

Lastly, JavaScript is ubiquitous: most of us are aware of JavaScript, or have used it sooner or later. Which means that transitioning to Node growth is probably simpler than to different server-side languages. To cite Craig Buckler in his Node vs PHP Smackdown, JavaScript would possibly stay the world’s most misunderstood language — however, as soon as the ideas click on, it makes different languages appear cumbersome.

Different Makes use of of Node

And it doesn’t cease on the server. There are various different thrilling and diversified makes use of of Node.js!

For instance it may be used as a scripting language to automate repetitive or error susceptible duties in your PC. It may also be used to put in writing your individual command line instrument, resembling this Yeoman-Fashion generator to scaffold out new tasks.

Node.js may can be utilized to construct cross-platform desktop apps and even to create your individual robots. What’s to not love?


JavaScript is in every single place, and Node is an unlimited and expansive topic. Nonetheless, I hope that on this article I’ve provided you the beginner-friendly, high-level take a look at Node.js and its principal paradigms that I promised in the beginning. I additionally hope that once you re-read the definitions we checked out beforehand, issues will make much more sense.

Node.js is an event-based, non-blocking, asynchronous I/O runtime that makes use of Google’s V8 JavaScript engine and libuv library.

In case you have any questions or feedback, be at liberty to hit me up on Twitter.

James Hibbard

Leave a Reply