DEV Community

Mario
Mario

Posted on • Originally published at mariokandut.com on

Getting started with Node.js

What is Node.js

Node.js is a free, open-sourced, cross-platform JavaScript run-time environment that lets developers write command line tools and server-side scripts outside of a browser. The runtime is built on Chrome's V8 JavaScript engine and was created by Ryan Dhal in 2009.

Since it's creation it got very popular and plays an important part in the development of web applications, but not only there, since you can build almost everything with it. The team who created Node.js took the core of Google Chrome, the V8 JavaScript engine, to run outside the browser. This gives Node.js the ability to leverage the work from Google engineers who build the Chrome V8 and it makes the runtime blazing fast and benefits from performance improvements and just-in-time compilations. In a nutshell, JavaScript code running in Node.js is very performant.

Node.js is an asynchronous event-driven JavaScript runtime and designed to build scalable applications.

Performance of a Node.js App

A Node.js app is running in a single process , without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives that prevent JavaScript code from blocking. Libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.

💰: Start your cloud journey with $100 in free credits with DigitalOcean!

When Node.js performs an I/O operation , like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.

This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.

Read more about performance in the official docs.

Additionally, you can use the new ECMAScript standards without problems, as you don’t have to wait for all your users to update their browsers - you are in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features by running Node with flags.

How to install Node.js

There are several, different ways to install Node.js. The two most used ones are:

Install from source

The easiest way to install Nodejs is from source, but this limits your option to have multiple versions of Nodejs installed. It can maybe cause permission errors in future projects. If you just want to use one version of Node:

    1. Download the latest Node.js source from Downloads
    1. After a successful download, double-click and install it.
    1. Open terminal and type node --version to see if it was successfully installed.

Install via NVM (recommended)

The recommended way to install Node is via NVM (Node Version Manager). The Node Version Manager is a bash script used to manage multiple released Node.js versions. It allows you to perform operations like install, uninstall, switch version, etc.

On Linux run the following commands:

    1. Install modules:
apk add -U curl bash ca-certificates openssl ncurses coreutils python2 make gcc g++ libgcc linux-headers grep util-linux binutils findutils
Enter fullscreen mode Exit fullscreen mode
    1. Download NVM:
curl -o- | bash https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh
Enter fullscreen mode Exit fullscreen mode
    1. Install latest Node.js LTS version:
nvm install --lts
Enter fullscreen mode Exit fullscreen mode

For macOS and Windows, please refer to the official docs.

How to run Node.js scripts

You can use the REPL or the CLI.

REPL

REPL also known as Read Evaluate Print Loop is a programming language environment, that takes single expression as user input and returns the result back to the console after execution.

You can use the interactive REPL for playing around, think of it as the console in the browser, or a console window.

  • Just type node in your terminal, and you will see that the welcome lineWelcome to Node.js v15.7.0. Type ".help" for more information..
  • To exit the REPL use CTRL+C or type .exit

CLI

The usual way to run a Node.js program is to run the node globally available command, once you've installed Node.js, and pass the name of the file you want to execute.

If your main Node.js application file is app.js, you can call it by typing:node app.js will run your app.js file.

While running the command, make sure you are in the same directory which contains the app.js file.

Simple Application

This example is a simple Hello World server.

Create a file named app.js.

touch app.js
Enter fullscreen mode Exit fullscreen mode

Copy the code below into the file app.js.

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 World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
Enter fullscreen mode Exit fullscreen mode

Now, run your web server using node app.js in the terminal, you have to be in the same folder, where the file app.js is located.

Visit http://localhost:3000 and you will see a message saying "Hello World".

Node.js Frameworks

By using a framework, you can work with a set of tools, guidelines, and recommended practices that help you save time and boost productivity.

Selecting a Node.js framework can be a bit tricky and subjective to its use case, because we choose based on a particular feature. This can is ranging from the weight of the framework on the application, speed, simplicity, learning curve, flexibility and configuration, use case or maybe even popularity in some cases. A friendly reminder: Github Stars aren't everything.

The following five Node.js frameworks I can highly recommend:

1. Express.js

Express.js is a fast, non-opinionated, minimalist web framework for Node.js and the most popular one. It behaves like a middleware to help manage servers and routes. It has a minimalist approach, is not opinionated and is focused on the core features of a server.

2. Meteor.js

Meteor is a very powerful full-stack framework, powering you with an isomorphic approach to building apps with JavaScript, sharing code on the client and the server. It’s major advantage is it’s realtime update, when changes occur on the web app, it automatically updates the template with the latest changes.

3. Koa.js

Koa.js is built by the same team behind Express.js, and it aims to be even simpler and smaller. Koa does not bundle any middleware within core, meaning the middlewares are more cascaded/streamlined, thereby allowing you to structure the parts however you want(component-based middlewares). This makes the framework to have more control over configurations and handling.

4. Next.js

Next.js is a framework to render server-side rendered React applications, and it got a massive boost in 2020.

5. Socket.io

Socket.io a real-time communication engine to build network applications.

Thanks for reading and if you have any questions , use the comment function or send me a message @mariokandut.

If you want to know more about Node, have a look at these Node Tutorials.

References (and Big thanks):

Node, OpenJSFoundation, scotch.io

Top comments (0)