Learn Node.js from Scratch (Step by Step)

Learn Node.js from Scratch (Step by Step)

Node.js is HUGE right now.

And it's getting bigger.

The question is:

How to learn node.js from scratch?

Well, that is what you will learn in this tutorial.

In this tutorial, I will share with you how to learn node.js from absolutely scratch step by step.

So, you don’t need to worry about you have not known node.js before.

Let's get start it.

 

1. What is Node.JS?

Node.js is a Javascript runtime built on the Chrome's V8 Javascript engine to make it easy to create fast and scalable network applications.

As explained in the official site nodejs.org:

nodejs

Node.js is not a programming language, but a runtime environment to execute javascript code on the server side.

So that it allows us to develop web applications using javascript as server-side programming language.

Like PHP, Python, Ruby and others.

Not just that, node.js also include many modules javascript libraries that can be used instantly.

like http modul, file system, and much more.

So, it can be concluded that node.js is a runtime environment + javascript library.

 

2. Why Using Node.js?

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

That why we are using the node.js.

For more details, the following is explained:

1. Asynchronous and Event Driven 

All Node.js API libraries are asynchronous, meaning, non-blocking. This basically means the Node.js-based server never waits for an API to restore data.

2. Very Fast

Built on Chrome's V8 JavaScript Engine, the Node.js library is very fast in code execution.

3. Single Threaded but Highly Scalable 

Node.js uses a single threaded model with looping events. 

The event mechanism helps the server to respond in a non-blocking and makes the server very scalable compared to traditional servers that make limited strings to handle requests. 

Node.js uses a single threaded program and the same program can provide services to a much larger number of requests than traditional servers such as Apache HTTP Server.

4. No Buffering 

Node.js applications never buffer any data. These applications simply output the data in chunks.

5. Licence

Node.jsis released under the MIT license.

 

3. Node.js Installation

To install node.js, please follow the following step by step:

1. Download node.js at official website https://nodejs.org/

node-js

2. And then install it like installing the application in general.

3. To make sure node.js is already installed on your computer, please open a terminal or Command Line / Command Prompt.

And then type the following command:

node -v

 

Then the output will be seen as follows:

node version

That means I have installed the node.js v8.11.3.

After that, also check NPM (Node Package Manager) by typing the following command:

npm -v

 

Then the output will be seen as follows:

npm

That means I have installed the NPM v5.6.0.

That’s it.

 

4. Basic Web Server in Node.js

To create a server on node.js, you can use the http module.

Why we need to create a server?

And how it works?

Let’s get start it.

1. First, create a javascript file with the name app.js.

Then open it with a text editor.

Here I use ATOM as a text editor.

Like the following picture:

app-js

2. Then write the following code:

const http = require('http');

http.createServer(function(req,res){
  res.writeHead(200,{
    "Content-Type" : "text/html"
  });
  res.end("Hello World");
}).listen(8000);

console.log('Server is running at port 8000');

3. Run app.js with the command in node.js terminal:

node app.js

 

Like the following picture:

server-listen

4. Open your browser, then type the url below:

http://localhost:8000

 

Then the output will look like this:

hello-world

 

5. Node.js and Express Framework

Express is a minimal and flexible Node.js web application framework that provides a range of advanced features for web and cellular applications.

Express has a myriad of HTTP utility methods and middleware that you want, making a powerful API fast and easy.

It might sound complicated, but it really isn't.

 

6. Express Installation

Before installing express, we should create package.json in our project.

To create package.json, just type the following command on the terminal node.js.

npm init

 

The above command will automatically create the package.json file for your project.

Then you can install express.

To install express, just type the following command on the terminal node.js.

npm install express --save

 

The above command will install express automatically into your project.

If the installation is complete, then you will occupy the folder named node_modules in your project as shown below:

project-structure

 

7. Basic Express Routing

Express makes it easy to define routes in node.js based applications.

Example:

I want to have two routes home and about.

Where the home route will display the text "Welcome to Express" and route about will display the text "This is about page".

Alright, let’s get start it.

First, open the app.js file that was previously created, then edit it to be like the following:

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

//route for home page
app.get('/',(req, res) => {
  res.send('Welcome To Express');
});

//route for about page
app.get('/about',(req, res) => {
  res.send('This is about page');
});

app.listen(8000, () => {
  console.log('Server is running at port 8000');
});

Second, run app.js by typing the following command on the terminal:

node app.js

 

Like the following picture:

server listen

Third, open your browser then type the following URL:

http://localhost:8000/

 

Then, the output will be seen as follows:

welcome to express

Then, to display the "about" page, type the following URL:

http://localhost:8000/about

 

Then, the output will be seen as follows:

about page

Simple right?.

 

8. Serving Static Files

Express provides the express.static middleware for serving static files, such as images, CSS, JavaScript, and others.

You only need to forward the name of the directory where you saved your static file to the express.static middleware to serve files directly.

For example, I want to serve bootstrap files.

Bootstrap consists of CSS and Javascript files.

Here, I have downloaded Bootstrap from the official site getbootstrap.com.

If you don't have bootstrap yet, please download it first.

After that, I created a directory that I named "public".

In the "public" folder, I copy the bootstrap files that was downloaded earlier.

Pay attention to the following picture for more details:

Public Folder

Then, we need to install the template engine.

Express supports many template engines.

In this case, I will use template engine handlebars.js.

To install handlebars, simply run the following command on the terminal node.js.

npm install hbs --save

 

The above command will install the view engine handlebars instantly on your project.

Next, create the views folder in your project directory. Then, create a file with the name index.hbs.

Pay attention to the following picture for more details:

views-folder

After that, follow step by step below:

1. First, open the index.hbs file using text editor then type the following html code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hello World</title>
    <!--Load bootstrap.css file-->
    <link rel="stylesheet" href="css/bootstrap.css"/>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <div class="jumbotron">
            <h1 class="display-4">Hello, world!</h1>
            <p class="lead">This is a simple site, a simple from mfikri.com.</p>
            <hr class="my-4">
            <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
          </div>
        </div>
      </div>
    </div>

    <!--Load bootstrap.js file-->
    <script src="js/bootstrap.js"></script>
  </body>
</html>

2. Second, open the app.js file, then edit it to be like the following:

//use path module
const path = require('path');
//use express module
const express = require('express');
//use hbs view engine
const hbs = require('hbs');
const app = express();

//set dynamic views file
app.set('views',path.join(__dirname,'views'));
//set view engine
app.set('view engine', 'hbs');
//set public folder as static folder for static file
app.use(express.static('public'));
//route for home page
app.get('/',(req, res) => {
  //render index.hbs file
  res.render('index');
});

//route for about page
app.get('/about',(req, res) => {
  res.send('This is about page');
});

app.listen(8000, () => {
  console.log('Server is running at port 8000');
});

3. Run app.js by typing the following command on the terminal node.js:

node app.js

 

Like the following picture:

server listening

Then, open your browser then visit the following URL:

http://localhost:8000/

 

Then, the output will be seen as follows:

hello world

Simple right?.

 

9. Sending Data to View

In this segment, you will learn how to send data to view.

Not only that, you will also learn how to retrieve data from URI parameters and send it to view.

Let's get start it.

1. First, open the app.js file, then edit it to be like the following:

//use path module
const path = require('path');
//use express module
const express = require('express');
//use hbs view engine
const hbs = require('hbs');
const app = express();

//set dynamic views file
app.set('views',path.join(__dirname,'views'));
//set view engine
app.set('view engine', 'hbs');
//set public folder as static folder for static file
app.use(express.static('public'));
//route for home page
app.get('/',(req, res) => {
  //render index.hbs file
  res.render('index',{
    name : "M Fikri"
  });
});

//route for home with params name
app.get('/:name',(req, res) => {
  //render index.hbs file
  res.render('index',{
    name : req.params.name
  });
});

app.listen(8000, () => {
  console.log('Server is running at port 8000');
});

2. Second, open the index.hbs file, then edit it to be like the following:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hello {{ name }}</title>
    <!--Load bootstrap.css file-->
    <link rel="stylesheet" href="css/bootstrap.css"/>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <div class="jumbotron">
            <h1 class="display-4">Hello, {{ name }}</h1>
            <p class="lead">This is a simple site, a simple from mfikri.com.</p>
            <hr class="my-4">
            <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
          </div>
        </div>
      </div>
    </div>

    <!--Load bootstrap.js file-->
    <script src="js/bootstrap.js"></script>
  </body>
</html>

3. Run app.js by typing the following command on the terminal node.js:

node app.js

 

Like the following picture:

server listening

After that, open your browser then type the following URL:

http://localhost:8000/

 

Then, the output will be seen as follows:

Hello MFikri

If you access with the following URL:

http://localhost:8000/From Express Js

 

Then, the output will be seen as follows:

Hello Express

 

10. Handling POST Request Body

In the previous segment you have learned how to handle requests via URI parameters.

In this segment, you will learn how to handle requests through the body.

To handle the POST request body, we need a "body-parser" middleware.

To install "body-parser", just type the following command on the terminal node.js:

npm install body-parser –save

 

The above command will install the body-parser middleware instantly to your project.

So, how to handle the POST request body?

Let’s get start it.

1. First, create a view with the name form.hbs as shown below:

form hbs

2. Open the form.hbs file, then write the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Add New</title>
    <!--Load bootstrap.css file-->
    <link rel="stylesheet" href="css/bootstrap.css"/>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <h2>Add New User</h2>
          <form action="/post" method="post">
            <div class="form-row">
              <div class="col">
                <input type="text" name="textname" class="form-control" placeholder="Name">
              </div>
              <div class="col">
                <button type="submit" class="btn btn-success">Submit</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!--Load bootstrap.js file-->
    <script src="js/bootstrap.js"></script>
  </body>
</html>

3. Open the app.js file, then edit it to be like the following:

//use path module
const path = require('path');
//use express module
const express = require('express');
//use hbs view engine
const hbs = require('hbs');
//use bodyParser middleware
const bodyParser = require('body-parser');
const app = express();

//set views file
app.set('views',path.join(__dirname,'views'));
//set view engine
app.set('view engine', 'hbs');

app.use(bodyParser.urlencoded({ extended: false }));
//set public folder as static folder for static file
app.use(express.static('public'));
//route home page
app.get('/',(req, res) => {
  //render index.hbs file
  res.render('index',{
    name : "M Fikri"
  });
});

//route for showing form
app.get('/post',(req, res) => {
  //render form.hbs file
  res.render('form');
});

//route for submit form by using post method
app.post('/post',(req, res) => {
  //render file form.hbs
  res.render('index',{
    //get value from textname
    name : req.body.textname
  });
});

app.listen(8000, () => {
  console.log('Server is running at port 8000');
});

4. Run app.js by typing the following command on the terminal node.js:

node app.js

 

Like the following picture:

server listening

And then, open your browser then type the following URL:

http://localhost:8000/post

 

Then, the output will be seen as follows:

add new

Enter the name in the textbox, and then submit.

Input name

Then the output will look like the following:

output post request body

 

Conclusion:

In this tutorial, we discussed about "learn node.js from scratch".

Node.js is a Javascript runtime built on the Chrome V8 Javascript engine to make it easy to create fast and scalable network applications.

In this tutorial you have learned from: what is node.js, why use node.js, node.js installation, basic web server on node.js, express framework, basic express routing, serving static files, sending data to view, and handle the POST request body.

So what are you waiting for, Let’s coding!

Download PDF

Comments (14)

Jimbo, 29 August 2018 16:20 -

How to store post to database ?

M Fikri, 03 September 2018 17:04 -

Coming soon.

M Fikri, 28 November 2018 14:09 -

Here:
https://mfikri.com/en/blog/nodejs-mysql-crud

Edi Kustriyadi, 15 March 2019 13:15 -

Thank's for sharing :)

M Fikri, 25 May 2019 21:28 -

You are welcome.

sifatullah, 14 May 2019 12:32 -

thanks alot sir it's so good and quality tutorial

M Fikri, 25 May 2019 21:28 -

You are welcome

David, 06 July 2019 13:50 -

Thanks for sharing this useful info.

Abhishek Agnihotri, 09 June 2021 19:58 -

Great Work ,

Ollie, 25 September 2021 18:12 -

restolin review My brother suggested I might like this website. He was entirely right. This post truly made my day. You can not imagine just how much time I had spent for this info! Thanks!

Leave a Comment