You are on page 1of 77

NodeJs Training

Glotech
Content
- Introduction
- Asynchronous programming
- Http server
- REST
- Express Js
- Database connection
Introduction
- Node.js is an open source server environment
- Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
- Node.js uses Google Javascript V8 Engine to execute code
- Everything inside Node.js runs in single thread
- Node.Js can be downloaded and installed at https://nodejs.dev/download/

C++
Node.js Hello World application
Node Package Manager

npm is the standard package manager for Node.js.

The NPM program is installed on your computer when you install Node.js

Install package:

npm install <package>

You can install the older version of module using

npm install <package>@<version>


Node Package Manager
Creating a project

1. Open terminal
2. Run the command `npm init` in the terminal. At this point you should be prompted
for some information. When you are done you should have a file called
`package.json` in your project
3. Running your first problem with following command `node <entry_file>`
Creating a project
The package.json configuration file
- The package.json file is kind of a manifest for your project. It can do a lot of things,
completely unrelated. It's a central repository of configuration for tools, for example.
It's also where npm store the names and versions for all the installed packages.

- Here's an example package.json file:

}
npm global or local packages

Local packages: are installed in the directory where you run npm install <package-
name>, and they are put in the node_modules folder under this directory

Global packages: are all put in a single place in your system (exactly where depends on
your setup), regardless of where you run npm install -g <package-name>

In general, all packages should be installed locally.

A package should be installed globally when it provides an executable command that you
run from the shell (CLI), and it's reused across projects.
npm dependencies and devDependencies

npm install <package-name> => installing it as a dependency.

Adding the -D flag, or --save-dev => installing it as a devDependencies list.

Development dependencies are intended as development-only packages, that are unneeded


in production. For example testing packages, webpack or Babel.

When you go in production, if you type npm install and the folder contains a package.json
file, they are installed, as npm assumes this is a development deploy.
The package.json configuration file
- name: application’s name
- version: application’s version
- description: brief description of the application
- main: application’s entry point
- scripts: list of scripts you can run
- dependencies: list of npm packages installed as dependencies
- devDependencies: list of npm packages installed as development dependencies

https://nodejs.dev/learn/the-package-json-guide
Exercise

Create your first Node.js program


Asynchronous programming
Synchronous vs Asynchronous
The Node.js Event Loop
- The Node.js JavaScript code runs on a single thread. There is just one thing
happening at a time.
- The event loop is in the heart of Node.js – it is responsible for scheduling
asynchronous operations.
The call stack
- The call stack is a LIFO (Last In, First Out) stack.
- The event loop continuously checks the call stack to see if there's any function that
needs to run.
- While doing so, it adds any function call it finds to the call stack and executes each
one in order.
The call stack
Queuing function execution
The Message Queue
- When setTimeout() is called Node.js starts the timer. Once the timer expires, in this
case immediately as we put 0 as the timeout, the callback function is put in the
Message Queue.
- The Message Queue is also where user-initiated events are queued before your code
has the opportunity to react to them.
- The loop gives priority to the call stack, and it first processes everything it finds in
the call stack, and once there's nothing in there, it goes to pick up things in the
message queue.
Asynchronous with Callbacks
- A callback function is one that is passed as an argument to another function, and then
executed when the other function is finished.
The problem with callbacks
- Callbacks are great for simple cases!
- However every callback adds a level of nesting, and when you have lots of callbacks,
the code starts to be complicated very quickly:
Asynchronous with Promises
- A promise is commonly defined as a proxy for a value that will eventually become
available.
- Once a promise has been called, it will start in a pending state. This means that the
calling function continues executing, while the promise is pending until it resolves,
giving the calling function whatever data was being requested.
- The created promise will eventually end in a resolved state, or in a rejected state,
calling the respective callback functions (passed to then and catch) upon finishing.
Asynchronous with Promises
The problem with Promises
Asynchronous with async/wait
- async makes a function return a Promise
Asynchronous with async/wait
- await makes a function wait for a Promise
Asynchronous with async/await
Understanding process.nextTick()
- Every time the event loop takes a full trip, we call it a tick. (when the call stack for
one event is empty)
- When we pass a function to process.nextTick(), we instruct the engine to invoke this
function at the end of the current operation, before the next event loop tick starts
Event loop execution order

Event loop executes tasks in process.nextTick queue first, and then executes promises
microtask queue, and then executes macrotask queue.
Event loop execution order
Node.JS event loop strategy
- Using setTimeOut, setImmediate, process.nextTick to run less importance task in
the current business code
Node.JS event loop strategy

Processor heavy works


Node.JS event loop strategy
- Web workers
Node.JS event loop strategy
Exercise

Build a guessing game


- User story: A user can enter a number
- User story: The system picks a random number from 1 to 6
- User story: If the user's number is equal to a random number, give the user 2 points
- User story: If the user's number is different than the random number by 1, give the
user 1 point. Otherwise, give the user 0 points
- User story: The user can play the game as long as they want to.
Exercise

Fetch country info from an API

If you open https://restcountries.herokuapp.com/api/v1/region/asia in a new browser, you


will see the country data in JSON format.

Write an nodejs application to read all country name of the given JSON API
Exercise
Write Node.Js application to read and process a big file.
- Write a program that will print out the total number of lines in the file.
- Notice that the 8th column contains a person’s name. Write a program that loads in this
data and creates an array with all name strings. Print out the 432nd and 43243rd names.
- Notice that the 5th column contains a form of date. Count how many donations occurred
in each month and print out the results
- Notice that the 8th column contains a person’s name. Create an array with each first
name. Identify the most common first name in the data and how many times it occurs.

Data: https://www.fec.gov/files/bulk-downloads/2018/indiv18.zip
Exercise

Investigate woker_threads
Http server
Http protocol
- HTTP is a protocol for fetching resources such as HTML documents
- HTTP is an extensible protocol which has evolved over time. It is an application
layer protocol that is sent over TCP, or over a TLS-encrypted TCP connection,
though any reliable transport protocol could theoretically be used
Http protocol
Http protocol
Http Server with Node.Js
Http Server with Node.Js
Exercise
- Create your first Http server to serve request from users
REST
- REST stands for REpresentational State Transfer.
- REST is web standards based architecture and uses HTTP Protocol.
REST resources

- Rest Resource is data on which we want to perform operation(s)


- This data can be present in database as record(s) of table(s) or in any other form.
- This record has unique identifier with which it can be identified like id for Employee.
REST

Anatomy of a REST API:


- POST (create a resource or generally provide data)
- GET (retrieve an index of resources or an individual resource)
- PUT (update/ replace a resource)
- PATCH (update/modify a resource)
- DELETE (remove a resource)
REST

For example, we are going to create a pretty common (and very practical) REST API for a
resource called users.
- POST on the endpoint /users (create a new user)
- GET on the endpoint /users (list all users)
- GET on the endpoint /users/:userId (get a specific user)
- PATCH on the endpoint /users/:userId (update the data for a specific user)
- DELETE on the endpoint /users/:userId (remove a specific user)
Express Js
Express Js
- Express.js is a Node js web application server framework, which is specifically
designed for building single-page, multi-page, and hybrid web applications.
- Express gets installed via the Node Package Manager. This can be done by executing
the following line in the command line

npm install express


Router
- Routers are simply an endpoint of a server. For example, facebook.com/dinhhuy258,
here the dinhhuy258 is a route.
- We can perform various operations on routes using HTTP methods such as GET,
POST, PUT, and DELETE.
Middlewares
- Middleware functions are functions that have access to the request object (req), the response
object (res), and the next middleware function in the application’s request-response cycle.
- Middleware functions can perform the following tasks:

+ Execute any code.

+ Make changes to the request and the response objects.

+ End the request-response cycle.

+ Call the next middleware function in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to
pass control to the next middleware function. Otherwise, the request will be left hanging.
Middlewares
Application-level middleware
- Bind application-level middleware to an instance of the app object by using the
app.use() and app.METHOD() functions
Router-level middleware
- Router-level middleware works in the same way as application-level middleware,
except it is bound to an instance of express.Router().
Error-handling middleware
- Error handling middleware in an application detect and capture multiple error
conditions and take appropriate remedial actions to either recover from those errors
or fail gracefully
- Error-handling middleware always takes four arguments. You must provide four
arguments to identify it as an error-handling middleware function.
Third-party middleware
- Use third-party middleware to add functionality to Express apps.
- Install the Node.js module for the required functionality, then load it in your app at
the application level or at the router level.
Exercise

1. Write Node.Js application to serve static files using Express.Js


2. Write Node.Js application to serve requests from clients using Express.Js
3. Using middleware to log client IP address for each request for the program above
Cookies
- A cookie is usually a tiny text file stored in your web browser
- A cookie was initially used to store information about the websites that you visit
Cookies
- Cookies are set using the Set-Cookie header field, sent in an HTTP response from the
web server
- Cookies are sent using Cookies header field in HTTP request from client to server
Cookies in Node.Js
- Using cookie-parser module
Sessions
- Session contains some unique data about that client to allow the server to keep track
of the user’s state
- In session-based authentication, the user’s state is stored in the server’s memory or a
database.
How sessions works
The difference between session and cookie
- A cookie is a key-value pair that is stored in the browser. The browser attaches
cookies to every HTTP request that is sent to the server.
- The session data is stored on the server-side
Where to store session
- Database
- Cache (redis…)
- In memory
Session in Node.Js
- Using cookie-parser, express-session modules
Exercise
1. Implement page view counter application for one user
2. Implement following pages
+ Home page
+ Login page
- The user must login before accessing the home page, otherwise it will redirect to the login page automatically.
- Functionality:

Login

Logout

Access homepage

3. Investigate JWT token


4. Try to setup session with cache/ database
Database
Postgres

PostgreSQL is a free, open source relational database management system.


Node.JS + Postgres

node-postgres, or pg, is a non-blocking PostgreSQL client for Node.js.

Essentially, node-postgres is a collection of Node.js modules for interfacing with a


PostgreSQL database.

npm install pg
Pg examples
Pg examples
Pg examples
Exercise

Create CRUD REST API to manage users


Extra
- DB migration: https://www.npmjs.com/package/node-flywaydb
- Typescript: https://nodejs.dev/learn/nodejs-with-typescript
- Node.JS project structure: https://blog.risingstack.com/node-js-project-structure-
tutorial-node-js-at-scale/

You might also like