31

Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries
Page 2: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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:

Page 3: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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.

Page 4: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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.

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.

Page 5: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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.

Page 6: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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/

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:

Page 7: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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

After that, also check NPM (package manager node) by typing the following

command:

npm -v

Then the output will be seen as follows:

That means I have installed the NPM v5.6.0.

That’s it.

Page 8: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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:

2. Then write the following code:

const http = require('http');

Page 9: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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:

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

http://localhost:8000

Page 10: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

Then the output will look like this:

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.

Page 11: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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:

Page 12: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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, () => {

Page 13: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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:

Third, open your browser then type the following URL:

http://localhost:8000/

Then, the output will be seen as follows:

Page 14: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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

http://localhost:8000/about

Then, the output will be seen as follows:

Simple right?.

Page 15: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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:

Page 16: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

Then, we need to install the template engine.

Express supports many template engines.

(https://github.com/expressjs/express/wiki#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:

Page 17: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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">

Page 18: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

<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');

Page 19: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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

Page 20: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

Like the following picture:

Then, open your browser then visit the following URL:

http://localhost:8000/

Then, the output will be seen as follows:

Simple right?.

Page 21: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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

Page 22: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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"/>

Page 23: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

</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:

Page 24: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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

http://localhost:8000/

Then, the output will be seen as follows:

If you access with the following URL:

http://localhost:8000/From Express Js

Then, the output will be seen as follows:

Page 25: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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.

Page 26: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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

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">

Page 27: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

<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

Page 28: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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

Page 29: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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:

Page 30: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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

http://localhost:8000/post

Then, the output will be seen as follows:

Enter the name in the textbox, and then submit.

Then the output will look like the following:

Page 31: Node.js is HUGE right now. The question ismfikri.com/files/Learn-NodeJs-From-Scracth.pdf · the Node.js-based server never waits for an API to restore data. All Node.js API libraries

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!

SOURCE: http://mfikri.com/en/blog/nodejs-tutorial