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¶
- Type in the terminal:
# For Debian-based Linux
apt install nodejs
# For Red Hat-based Linux
dnf install nodejs
- Make sure nodejs is installed by checking the version:
nodejs --version
# v14.17.1
Run JavaScript Code¶
- Type in terminal
nodejs
. - You will be prompted by the nodejs console. You can type Javascript Code in that console.
let myname = "Nawras";
console.log(`Hello ${myname}`);
- You can see Hello Nawras displayed in the console.
- Type the following in the console:
let result = (a, b) => a + b;
result(6, 10); // 16
Execute a file¶
- 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());
- Run it using nodejs:
nodejs myfile.js
- 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.
- Add the following code to the task1.js file:
for (let i=10; i<=20; i++){
console.log(i);
}
- Run the code using nodejs:
nodejs task1.js
- 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.
- 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]}`);
}
- Run the code using nodejs:
nodejs task2.js
- 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.
- Add the following code to the task3.js file:
let arr = ['first', 'second', 'third'];
for(let item of arr){
console.log(item);
}
- Run the code using nodejs:
nodejs task3.js
- You get the following result:
first
second
third