Skip to content

Introduction to Node.js

What is Node.js?

Node.js is an open-source platform that executes Javascript code outside the browser. Node.js is also a popular framework to build websites.

Installing Node.js

Windows

Check the wikiHow tutorial

Linux

  1. Type in the terminal:
# For Debian-based Linux
apt install nodejs
# For Red Hat-based Linux
dnf install nodejs
  1. Make sure nodejs is installed by checking the version:
nodejs --version
# v14.17.1

Run JavaScript Code

  1. Type in terminal nodejs.
  2. You will be prompted by the nodejs console. You can type Javascript Code in that console.
let myname = "Nawras";
console.log(`Hello ${myname}`);
  1. You can see Hello Nawras displayed in the console.
  2. Type the following in the console:
let result = (a, b) => a + b;
result(6, 10); // 16

Execute a file

  1. Create a Javascript file with the name "myfile.js", and type the following in it:
function isValid(password){
    return password ? password.length >= 8 : "Password can NOT be empty";
}
console.log(isValid('12345678'));
console.log(isValid(''));
console.log(isValid('1234'));
console.log(isValid());
  1. Run it using nodejs:
nodejs myfile.js
  1. You get the following results:
true
Password can NOT be empty
false
Password can NOT be empty

Practice

Task 1: Write a code that logs the numbers from 10 to 20 out in the console. Run the file using nodejs.

  1. Add the following code to the task1.js file:
for (let i=10; i<=20; i++){
    console.log(i);
}
  1. Run the code using nodejs: nodejs task1.js
  2. You get the following result:
10
11
12
13
14
15
16
17
18
19
20

Task 2: Write a code that creates an object and prints out that object entries. Run the file using nodejs.

  1. Add the following code to the task2.js file:
let myObject = {
    name: "Nawras",
    mark: 0
};

for (let key in myObject){
    console.log(`${key}: ${myObject[key]}`);
}
  1. Run the code using nodejs: nodejs task2.js
  2. You get the following result:
name: Nawras
mark: 0

Task 3: Write a code that creates a new array and displays its values in the console. Run the file using nodejs.

  1. Add the following code to the task3.js file:
let arr = ['first', 'second', 'third'];
for(let item of arr){
    console.log(item);
}
  1. Run the code using nodejs: nodejs task3.js
  2. You get the following result:
first
second
third