Nodejs & Express
Waverley Software Vietnam
2018 - v1.0
Triet Ho
Audiences & Objectives
Ø Audiences
ü Developer
ü Anyone want to get started with Nodejs
Ø Objectives
ü Understand what Nodejs and Nodejs Express are
ü Create a Hello World web app with Nodejs Express framework
ü Using Express framework with EJS View Engine
ü Start to learn further about Nodejs and Express
Ø Time: 90 minutes
Table of Content
ØIntroduce Nodejs
ü Compare javascript in browser and nodejs
ü Install and Hello World
ü Function, callback, module, class, object
ü Node Package Manager (NPM)
Ø Nodejs Express framework
ü Project structure
ü Routes
ü View Engine (EJS)
ü Middleware
ØCommon Nodejs Packages
ØUse PM2 to manage Nodejs apps hosting
Introduce Nodejs
About Nodejs
Ø In short: Node
Ø Language: Javascript
Ø Can do:
ü Server App: Web App, Web API, Socket server…
ü Client App: Console, cron jobs
Ø Cannot do:
ü GUI app (Win forms)
How javascript executed
Ø Browser vs Node
Chrome.exe Nodejs.exe
Web pages
Javascript files (.js)
HTML CSS Javascript
Rendering V8 Javascript Engine
V8 Javascript Engine
Engine
Node Standard Libraries Event Loop
(socket, http, file system…) libuv
How nodejs work
5
4
Worker Pool
0 Javascript files 3 File system
Task(cb)
function1(callback) 1 2
function2(callback) V8 Event loop Task(cb) Network
function3(callback)
Task(cb) Database
…
Expensive tasks
0 – Trigger method calls in parallel (e.g: response to a user’s requests)
1 – The function scripts are interpreted and send to event loop – the main thread to listen the events
2 – The main thread registers the task’s callback and distributes the task to the worker pool
3 – The real task business is handled
4 – Announce the event loop when the task completed
5 – Trigger the callback to the caller
Install Nodejs and Hello World
Ø Install via installer or download portable version
ü https://nodejs.org/en/download/
ü Installer is recommended (include NPM by default)
Ø Hello World Console
ü Create a text file name hello.js with this line:
• Console.log('Hello World’)
üOpen command line console, and move to hello.js folder, type:
• node hello.js
ØHello World Web app
ü https://nodejs.org/docs/latest-v9.x/api/synopsis.html
Ø Recommended code editors: Visual Studio Code, NetBeans
Functions
Callbacks
Function that will be called back to the caller, return the result asynchronous
Module
Ø Each js file is a module
Ø A module can expose
ü Class, Object
ü Function, and Constant
Ø Expose by “exports” keyword
Ø Using module by “require” method
Module – export class
Class
NPM – Nodejs package manager
Ø Included in Nodejs Installer
ØUse to install/update/uninstall node modules from public repository
(npmjs.com)
Ø Initial a Node project: npm init
ü It will create package.json
ü Where define project info and packages to be used
Ø Install all packages in package.json: npm install
ØInstall a package global: npm install package-name -g
Ø Install a package locally: npm install package-name –save
Express
Introduce Nodejs Express
About Express
Ø Web app framework for Nodejs
Ø As a node module, named: express
Ø Install: npm install express –save
Ø A simple express app
Ø Express website: https://expressjs.com/
Express Generator
Ø An express tool to generate the application skeleton
Ø Install the tool
ü npm install express-generator –g
Ø Create an app with ejs view engine:
ü express --view=ejs myDemo
ØExpress Generator: https://expressjs.com/en/starter/generator.html
Express framework
Ø\bin\www
ü starting point of the app: load express and start a web server
Øapp.js
üStarting point of express: mapping routes (urls) handling, and middleware
Ø\public\
ü root folder for the static contents that send to browsers directly
ü e.g: javascript, images, css, files for download...
Ø\views\
ü Content templates that will be used to fill in data and send to clients
Ø \routes\
ü handling requests and response to clients
Express – request handling
http://localhost:3000/about
Client
Server
Routing handling
ØRoute paths
üMake up the url
üSupport Regular expressions
Ø Handle HTTP methods
ü app.get(routepaths, handler), app.post(…), etc
üapp.all(…): catch all HTTP methods
üMore info: https://expressjs.com/en/guide/routing.html
Route parameters
Ø placeholders for url parts
Ø:paramname
ü Word characters ([A-Za-z0-9_])
• :userid
• :bookId
Øhttps://expressjs.com/en/guide/routing.html
View Engine (EJS)
Ø Common tags
üControl flow with <% %>
üEscaped output with <%= %>
üUnescaped raw output with <%- %>
Ø https://www.npmjs.com/package/ejs
Middleware
Ø Execute any code.
Ø Make changes to the request and the
response objects.
Ø End the request-response cycle.
Ø Call the next middleware in the stack.
Common Nodejs modules
Ø async: control async calls
Ø request: make http request
Ø moment: manipulate time
Ø validator: validate common data (email, url, phone…)
Ø pm2: node process management
Ø mongosee: access to mongodb
Ø passport: authentication framework
Ø…
PM2
Ø Process Manager for Nodejs applications
ü built-in load balancer
ü auto reload on crash
ü Support starting apps when system restart
ü Logging and monitoring
ü Multiple app definitions in file (ecosystem file)
ü (It is not a web server)
Ø Common commands
ü Install: npm install pm2 -g
ü Start apps: pm2 start ecofile.js
ü Show app list: pm2 ls
ü Show log console: pm2 log <appid>
ü More info: https://pm2.io/doc/en/runtime/guide/