Node.js Tutorial – The ultimate Guide for beginners

Node.js Tutorial – The ultimate Guide for beginners Thumbnail
Published on 31. May 2020Last updated on 19. June 2020

This Node.js tutorial is for all developers who want to program with Node.js, but know little or nothing about it – so complete beginners in this area. Node.js is becoming more and more popular and every web developer should at least know the basics. After this tutorial, you can definitely count yourself in this group.

Advertisement

This Node.js tutorial is very practically oriented. Nevertheless I will start with a short description of the functionality, application area and installation. From chapter 3 on the practical part starts.

So that you have a red thread through this tutorial, I have summarized the points for you.

1. What is Node.js?

With Node.js the script language JavaScript has also found its way into server-side programming. Before Node.js, JavaScript was mainly only responsible for the frontend and the interaction with the visitor.

With Node.js, however, it is now possible to develop everything from small CLI (command line) tools to complex programs and stand-alone HTTP servers. Exactly this universal applicability is what makes Node.js so brilliant for me personally – and for many other developers, too!

And for what do I need Node.js now?

When a website is called, the JavaScript code is executed on the visitor’s side, i.e. on the client side. With Node.js, however, JavaScript is executed on the requested server, i.e. server-side. This is the most obvious difference and sounds unspectacular at first.

However, this fact changes most of the areas of application of JavaScript. In the browser, JavaScript is mainly responsible for the manipulation at the DOM. In Node.js this task is omitted and it is available for the return of data. Node.js can also connect to a database (e.g. MySQL or MongoDB).

So Node.js acts as a kind of web server. At this point we will continue and write our own web server with Node.js in this tutorial.

All right?

Now if you are wondering if you really need and want to use Node.js, you should read the most frequently asked questions below and decide if Node.js is the right technology for you.

Advertisement

Another important reason for the success are the onboard resources that come in with Node.js. From scratch Node.js already has many functions and modules that are easy to use. And to make the system even more perfect, there is the package manager – also called npm (Node Package Manager). You will find more information about this later under Node.js Modules. Anyway, it’s very easy to add new features, i.e. extensions from other developers and the Node.js community.

That sounds promising at first, of course, but can you already imagine something concrete? Probably not really. At least it wouldn’t be very easy for me to read something like this on a topic I’m not familiar with. So it’s best to read this section again at the end of this article and I assure you, you will know what I’m talking about 😉

2. Install Node.js

Before we can start with the actual programming, we first have to install Node.js on our computer. To do this, select your operating system on which you want to develop. Windows or Mac…?

2.1 Windows

Under Windows you can simply download the installer and follow the installation instructions. It is best to download the LTS (Long-term support) version as it is already established and has fewer bugs than the latest version.

Windows Installer

2.2 Mac

On the Mac, just like Windows, you can download the official installer and follow the installation instructions. It is best to download the LTS (Long-term support) version as it is already established and has fewer bugs than the latest version.

Mac Installer

2.3 Node.js App Hosting (food for thought)

If you manage your domains with Plesk and want to host your app there, all you need is the Node.js extension, which you can download with a single click.

Advertisement
Plesk Interface - Installing the Node.js Extension
Plesk Interface – Installing the Node.js Extension

However, for development you should work locally on your Mac or Windows computer. When your app is finished and you want to deploy it (go live), you can use this instruction to help you.

You should also keep this in mind, but it is not important for the beginning, it only happens in the last step.

3. Understand the CLI

CLI stands for Command-Line Interface and means command line. On the Mac you can use the preinstalled program “Terminal” and under Windows the command prompt (cmd.exe).

cmd.exe from Windows
cmd.exe von Windows

With this we can control Node.js. With the command node we can now execute any JavaScript commands. In the further course of this article you will now know what you can understand by the CLI.

We need the CLI, because it is used to start and stop our app and to display errors of our app. More about this later.

4. Node.js Modules

The crown jewels of Node.js are its modules. At the beginning I already mentioned that Node.js has a package manager. The shortcut and command for the CLI is npm (Node Package Manager).

NPM is a gigantic network of development tools that you can download free of charge for your application. If you work with Node.js, you will find that you always have to and should use modules from other developers. You don’t have to reinvent the wheel all the time.

In this example we download the express module. This works with the following command.

Advertisement
npm install express

You can also install modules globally, which means it applies to your entire computer and is not only available in one project. To do this, you simply append the parameter -g.

npm install -g express

When you install a module, the node_modules folder is automatically created. This folder contains all installed modules and can normally be ignored by you. We can include a module in the code later like this:

const express = require('express');

5. First project

5.1 Create project folder

The time has come, we finally start programming. To create a Node.js project, we simply create a normal folder in any directory. In this folder we create an index.js, which is our start file.

Created folder with the start file index.js
Created folder with the start file index.js

5.2 Initialize Node.js App

Now we have to say in this folder that we want to turn it into a Node.js app, we do this with this command in the CLI:

npm init

We are asked for various parameters, such as package name, version and description. You can fill out these fields or just leave them on default settings like me. We can change these settings later on in the package.json.

Console output after the npm init command
Console output after the npm init command

5.3 Get to know package.json

A package.json file has now been created in our folder. This file contains all information about our application, such as the author, version and most importantly, all installed dependencies (modules).

// package.json

{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Currently you do not need to do anything more with it, but it will become important.

5.4 Writing program code

Now we can write the first JavaScript code in our index.js. Of course we cannot do without it and have to output “Hello World”.

// index.js

console.log('Hello World');

5.5 Test the application

The first code is written and we want to start our program. We do that through this command:

Advertisement
node index.js

We get the following result, cool! ?

"Hello World" issue of our 1st Node.js app
“Hello World” issue of our 1st Node.js app

Granted, at the beginning of the Node.js tutorial it all sounded much cooler. But don’t worry, there is more to it. 🙂

You can try JavaScript functions in this file, for example, to simply add two numbers and output them to the console. Just play around with it for 5 minutes and then read on.

You can’t always find a suitable tutorial on the Internet, so a reference book for Node.js* can be a great help.

6. Improve workflow – with Nodemon

It’s really annoying when we have to restart our Node.js app manually after every small change to the code, isn’t it? Right, that’s why there is the module nodemon, which we install globally. This module detects file changes and restarts the Node.js app within milliseconds. This speeds up our workflow enormously.

npm install -g nodemon

After the installation we start Nodemon with this command and directly our app is started and restarted automatically if changes are made.

nodemon index.js

If you now save your files inside the project folder, the Node.js app will restart automatically.

Improved workflow - thanks to Nodemon
Improved workflow – thanks to Nodemon

7. Node.js Webserver – Outputting content to the browser

7.1 Setting up a web server

So far so good. We can write and execute functions and output text from the console. However, the user of our application has none of this, since he can only access it via the browser.

Advertisement

Therefore, we are now setting up a web server and delivering content to the user in the browser. Exactly the same happens when a website is called.

To do this, we install the express module using the following command, if not already done in step 4:

npm install express

And we adjust our index.js as follows:

// index.js

const express = require('express');
const app = express();

app.get('/', (request, response) => {
  response.send('Our first Node.js webserver');
});
app.listen(3000, () => console.log('Server running on port 3000'));

To help you understand everything, here is an explanation line by line:

LineDescription
Line 3Integration of the express module.
Line 4Initialization of the express module in the variable app.
Line 6We intercept the page request from / our server to be able to perform an action. Such a call is called a route.
Line 7We send the text “Our first Node.js webserver” back to the inquirer as an answer.
Line 9We start our web server on port 3000 and display a message in the console.
Line by line explanation of the first Node.js web server (Express)

If we ask for browser now our computer on port 3000, we get this result:

Browser view when calling our Node.js web server application
Browser view when calling our Node.js web server application

Simple, isn’t it? That’s why Node.js is so genius. You only need seven lines of code for your own web server.

7.2 Rest API Basics – Parameters in Routes

If we now adjust our route a little bit, we can return data already transferred:

// index.js

const express = require('express');
const app = express();

app.get('/:yourName', (req, res) => {
  res.send('Your name: ' + req.params.yourName);
});
app.listen(3000, () => console.log('Server running on port 3000'));

Here :yourName stands for a variable string (note the colon!) that we can pass in our URL and with req.params.yourName we can read it and send the name back to the user.

If we now call http://localhost:3000/test, we get the string with the given name as answer. So you can already read and send data with really little code.

Advertisement

This procedure is the basis for creating a Rest API.

8. Deploy Node.js App (publish)

Many Node.js tutorials forget to show how to finally deploy (publish) a Node.js app. Most of the time they just stop after the basics.

You can of course run your app locally, but it doesn’t make sense if you want to share an application with others.

A free way to host Node.js apps is Heroku. Just follow this guide. The free model at Heroku of course does not have all the features, e.g. you cannot use your own domain.

Another way to deploy a Node.js app is to have your own server with Plesk as management software. Such servers are already available for less than 10 Euro per month and are perfectly suited for development, testing and productive use! To deploy Node.js Apps with Plesk you can find a tutorial here.

9. FAQ – Frequently asked questions

When do I use Node.js?

Node.js is primarily used for “normal” dynamic websites and backend APIs (Rest APIs). In addition, Node.js is often used for applications that need to process data in real-time (e.g. chats).

Is Node.js a programming language?

Definitely no. Node.js combines the scripting language JavaScript and a network component. Since Node.js was developed on the Google V8 JavaScript engine, Node.js is able to handle basic network technology such as the HTTP, DNS and TCP protocols.

Is it easy to learn Node.js?

Since Node.js is neither a framework nor a programming language, you have to rather ask yourself if it is easy to learn JavaScript. Surveys have shown that JavaScript is one of the easiest scripting languages to learn.

Advertisement
What is a middleware?

A middleware is a partial program, i.e. a function that is executed between two components. For example, when the user calls /settings, the actual program code should only be executed when the user is logged on. To do this, you write a middleware function and call this function in front of it. You do this so that you can use the same code (checking the login) several times, but only have to write it once.

How and where can I host a Node.js app?

Node.js apps can be hosted for free at Heroku, for example. But if you have your own server, you can host your own Node.js app for free in Plesk. I have created a complete guide for this here.

What does the package.json do?

The package.json for Node.js apps contains information about the name, the author, and much more. Most important are the dependencies. This is a list of the modules (dependencies) your app uses. You can also define commands under scripts to execute or test your app.

What does the node_modules folder do?

The node_modules folder contains all modules included in your node.js. This includes standard modules, but also all additional modules you have installed and listed in package.json under scripts. You don’t need to push the node_modules folder into your git repository or live hosting, because the command npm install will download all modules into the folder again.

This is too much for me. How do I find a suitable Node.js Developer?

That’s no problem either. The colleagues from toptal.com have published a guide to this.

Next steps

Whew! That’s a lot of information, isn’t it? Nevertheless, I hope you got a good impression of what is possible with Node.js and that I made you curious for more.

What happens now? If you want to get directly involved in a larger but very interesting project, this article shows you how to create a login system with Node.js. We will specifically address database connection and the creation of a Rest API.

You are welcome to write unresolved questions in the comments! 🙂

Related Posts
NEW 🚀
Join the Conversation

3 Comments

Your email address will not be published. Required fields are marked *