Getting started with Node.js
© https://nodejs.org/en/

Getting started with Node.js

Introduction to Node.js and how to run JavaScript outside the browser.

ByMario Kandut

honey pot logo

Europe’s developer-focused job platform

Let companies apply to you

Developer-focused, salary and tech stack upfront.

Just one profile, no job applications!

This article is based on Node v16.14.0 and nvm v0.35.

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.

💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.

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.

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.

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
    1. Download NVM:
curl -o- | bash https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh
    1. Install latest Node.js LTS version:
nvm install --lts

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 line Welcome 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

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}/`);
});

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

More node articles:

Getting started with Webpack

How to list/debug npm packages?

How to specify a Node.js version

How to create a web server in Node.js

How to dynamically load ESM in CJS

How to convert a CJS module to an ESM

How to create a CJS module

How to stream to an HTTP response

How to handle binary data in Node.js?

How to use streams to ETL data?

How to connect streams with pipeline?

How to handle stream errors?

How to connect streams with pipe?

What Is a Node.js Stream?

Handling Errors in Node (asynchronous)

Handling Errors in Node.js (synchronous)

Introduction to errors in Node.js

Callback to promise-based functions

ETL: Load Data to Destination with Node.js

ETL: Transform Data with Node.js

ETL: Extract Data with Node.js

Event Emitters in Node.js

How to set up SSL locally with Node.js?

How to use async/await in Node.js

What is an API proxy?

How to make an API request in Node.js?

How does the Event Loop work in Node.js

How to wait for multiple Promises?

How to organize Node.js code

Understanding Promises in Node.js

How does the Node.js module system work?

Set up and test a .env file in Node

How to Use Environment Variables in Node

How to clean up node modules?

Restart a Node.js app automatically

How to update a Node dependency - NPM?

What are NPM scripts?

How to uninstall npm packages?

How to install npm packages?

How to create a package.json file?

What Is the Node.js ETL Pipeline?

What is data brokering in Node.js?

How to read and write JSON Files with Node.js?

What is package-lock.json?

How to install Node.js locally with nvm?

How to update Node.js?

How to check unused npm packages?

What is the Node.js fs module?

What is Semantic versioning?

The Basics of Package.json explained

How to patch an NPM dependency

What is NPM audit?

Beginner`s guide to NPM

Getting started with Node.js

Scroll to top ↑