SlideShare a Scribd company logo
Fundamental Node.js
By Warsono Muhamad Faizal
Current Position:
Frontend Web Developer at GITS Indonesia
Formerly:
Backend Web Developer at Panenmaya Digital
Email:
warsono16694@gmail.com
Website:
https://warsono.id
Social Media:
Github: /gravitano
Linkedin: /in/gravitano
Medium: @gravitano
Instagram: /warsonoid
Warsono Muhamad Faizal
Frontend Web Developer
Agenda
● Introduction to Node.js
● Asynchronous Programming
● Basic JavaScript
● Web Server with Node.js
● Express.js
● Build App with Express.js
Let’s Get Started
What is Node.js?
● Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine.
● It was created by Ryan Dahl in 2009
● It uses an event-driven, non-blocking I/O model that makes it lightweight
and efficient.
● It’s an asynchronous event-driven JavaScript runtime, which is designed to
build scalable network applications.
● It can handle many concurrent connections at a time, where when
connection request are made concurrently for each connection a callback
is fired.
● In a simple words, Node.js is “server-side JavaScript”
Why Node.js?
● It is asynchronous (non-blocking)
● Very fast! It is much faster than Ruby, Python, or Perl.
● Ability to handle thousands of concurrent connections with minimal
overhead on a single process
● Single-threaded but highly scalable
● Node.js is very reliable especially for making real-time applications
● Single programming language for client and server
Who’s using Node.js?
● GoDaddy
● Groupon
● IBM
● LinkedIn
● Microsoft
● Netflix
● PayPal
● Walmart
● More...
Node.js Frameworks
● Express: It provides one of the most simple yet powerful ways to create a
web server. Its minimalist approach, unopinionated, focused on the core
features of a server, is key to its success.
● AdonisJs: A full-stack framework highly focused on developer ergonomics,
stability, and confidence. Adonis is one of the fastest Node.js web
frameworks.
● NestJS: A TypeScript based progressive Node.js framework for building
enterprise-grade efficient, reliable and scalable server-side applications.
● Socket.io: A real-time communication engine to build network
applications.
Asynchronous Programming
Synchronous JavaScript
● JavaScript code runs on a single thread (can do 1 thing at a time)
● Synchronous code waits for 1 action to complete before moving on to the
next
Asynchronous JavaScript
● An asynchronous model allows multiple things to happen at the same
time.
● When you start an action, your program continues to run.
Demo
Synchronous VS Asynchronous
http://bit.ly/sync-async
Basic JavaScript with Node.js
Warning!
● Program for Node.js are written in JavaScript
● There is no DOM implementation provided by Node.js, i.e. you can not do
this:
document.getElementById(‘element’);
window.alert(‘Hello’);
Preparation
https://github.com/gravitano/ws-fundamental-nodejs
atau
http://bit.ly/ws-nodejs
Basic JavaScript - Console
var myString = "Hello World";
var myObject = {
hello: "World"
};
console.log(myString);
// alias for console.log
console.info(myObject);
console.warn("Warning!");
// Displays data as a table.
console.table([{ a: 1, b: "Y" },
{ a: "Z", b: 2 }]);
// Starts a timer you can use
// to track how long an operation
takes
console.time("benchmark");
for (var i = 0; i < 100; i++) {}
console.timeEnd("benchmark");
console.trace("Show me");
Basic JavaScript - Variable : Var/Let/Const
var hello = "Hello";
let world = "World";
const helloWorld = "Hello" + " " + world;
const myString = new String("This is a string");
var hello = "Halo";
let world = "Dunia";
// SyntaxError: Identifier 'world' has already been declared
const myString = "Ini sebuah string";
// SyntaxError: Identifier 'myString' has already been declared
console.log(hello, world, myString);
Basic JavaScript - Boolean
● Truthy
○ 1
○ -1
○ '1'
○ 'abc'
○ ' '
○ true
○ {}
○ []
○ Infinity / -Infinity
○ function(){} / () => {}
● Falsy
○ false
○ ''
○ 0
○ null
○ undefined
○ NaN
Basic JavaScript - Conditional
const price = 1000;
if (price <= 1000) {
console.log("Small");
} else if (price > 1000 && price < 5000) {
console.log("Medium");
} else {
console.log("Large");
}
const status = "pending";
switch (status) {
case "pending":
console.log("Pending");
break;
case "approved":
console.log("Approved");
break;
default:
console.log("Unknown");
break;
}
Basic JavaScript - Looping
// loops through a block of code a number of
times
for (let i = 0; i < 5; i++) {
console.log("The number is " + i);
}
// loops through the properties of an object
const person = { firstName: "John",
lastName: "Doe", age: 25 };
for (key in person) {
console.log(key, person[key]);
}
// loops through the values of an iterable
object
var cars = ["BMW", "Volvo", "Mini"];
for (car of cars) {
console.log(car);
}
// loops through a block of code while a
specified condition is true
let i = 0;
while (i < 10) {
console.log("The i number is " + i);
i++;
}
// also loops through a block of code
while a specified condition is true
let j = 0;
do {
console.log("The j number is " + j);
j++;
} while (j < 10);
Basic JavaScript - Function
function showMessage() {
console.log("Weather information");
}
const toCelsius = function(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
};
const showWeatherInfo = function(fahrenheit) {
console.log("Info: ", toCelsius(fahrenheit));
};
// arrow function
const myFunction = () => 43;
const myFunction2 = text => {
return text;
};
const myFunction3 = (param1, param2) => {
return `${param1}, ${param2}`;
};
// calling function
showMessage();
console.log(toCelsius(42));
showWeatherInfo(70);
Basic JavaScript - Module
// file: module/math.js
const add = (x, y) => x + x;
const subtract = (x, y) => x - y;
module.exports.add = add;
exports.subtract = subtract;
// file: module/app.js
const math = require("./math");
// es6
const { add, subtract } = require("./math");
console.log(math.add(10, 2)); // 20
console.log(math.subtract(10, 2)); // 8
console.log(add(10, 2)); // 20
console.log(subtract(10, 2)); // 8
Basic JavaScript - Module : Export as object
const add = (x, y) => x + x;
const subtract = (x, y) => x - y;
module.exports = {
add: add,
subtract: subtract
};
module.exports = {
add, // es6 shorthand for add: add
subtract
};
Basic JavaScript - Module : Default Export
// file: module/add.js
const add = (x, y) => x + x;
module.exports = add;
// file: module/app3.js
const add = require("./add");
console.log(add(10, 2)); // 20
Basic JavaScript - Callback
● A callback is a function that is to be
executed after another function has
finished executing — hence the name
‘call back’.
● In JavaScript, functions are objects.
Because of this, functions can take
functions as arguments, and can be
returned by other functions.
● Functions that do this are called
higher-order functions.
● Any function that is passed as an
argument is called a callback function.
setTimeout(function() {
console.log(1);
}, 500);
$('#my_button').on('click', function(e) {
console.log('Ouhh aku di klik!');
})
Basic JavaScript - Promise
● The Promise object is used for deferred and asynchronous computations.
● A Promise represents an operation that hasn't completed yet, but is expected in
the future.
Basic JavaScript - Promise : Example 1
const fs = require("fs");
// contoh promise untuk async
const promiseAsync = new
Promise((resolve, reject) => {
fs.readFile(__dirname + "/hello.txt",
"utf8", (err, res) => {
if (err) reject(err);
resolve(res);
});
});
promiseAsync
.then(res => console.log("Hasil Async:
", res))
.catch(err => console.log("error",
err));
// contoh promise untuk sync
const promiseSync = new Promise(resolve
=> {
resolve("Hello Sync");
});
promiseSync.then(res =>
console.log("Hasil Sync: ", res));
Basic JavaScript - Promise : Example 2
const fs = require("fs");
const getData = filename => {
return new Promise((resolve, reject) => {
fs.readFile(__dirname + "/" + filename,
"utf8", (err, res) => {
if (err) reject(err);
resolve(res);
});
});
};
getData("data.json")
.then(result => {
console.log("result", result);
console.log(typeof result);
return JSON.parse(result);
})
.then(result2 => {
console.log("result 2", result2);
console.log(typeof result2);
})
.catch(err => {
console.log("Whoops! Something went
wrong...");
console.error(err);
});
Basic JavaScript - Promise : Example 3
const promise1 = new Promise(resolve => {
setTimeout(() => {
resolve(1);
}, 5000);
});
const promise2 = new Promise(resolve => {
setTimeout(() => {
resolve(2);
}, 1000);
});
Promise.race([promise1, promise2]).then(res =>
{
console.log(res);
});
Promise.all([promise1, promise2]).then(res =>
{
console.log(res);
});
Basic JavaScript - Async/Await
● Async and Await are extensions of
promises
● Async functions enable us to write
promise based code as if it were
synchronous, but without blocking the
execution thread.
● Async functions will always return a
value
● Using async simply implies that a
promise will be returned, and if a
promise is not returned, JavaScript
automatically wraps it in a resolved
promise with its value.
async function firstAsync() {
return 27;
}
firstAsync().then(alert); // 27
Basic JavaScript - Async/Await : Example
async function firstAsync() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Now it's done!"), 500);
});
// wait until the promise returns us a value
let result = await promise;
// "Now it's done!"
console.log("result:", result);
}
firstAsync();
Basic JavaScript - Async/Await
Things to remember when using Async
Await
● We can’t use the await keyword inside
of regular functions.
● Async Await makes execution
sequential
// error
function firstAsync() {
let promise = Promise.resolve(10);
let result = await promise; // Syntax error
}
async function sequence() {
await promise1(50); // Wait 50ms…
await promise2(50); // …then wait another
50ms.
return "done!";
}
Web Server with
Node.js
Web Server - Hello World Example
const http = require("http");
const hostname = "127.0.0.1";
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello World");
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Web Server - Render HTML
const http = require("http");
const fs = require("fs");
const hostname = "127.0.0.1";
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
const content = fs.readFileSync(__dirname + "/index.html");
res.end(content);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
const http = require("http");
const data = require("./data.json");
const hostname = "127.0.0.1";
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
const content = JSON.stringify(data);
res.end(content);
});
server.listen(port, hostname, () => {
console.log(`Server running at
http://${hostname}:${port}/`);
});
Web Server - Render JSON
[
{
"id": 1,
"name": "Warsono"
},
{
"id": 2,
"name": "Andy"
},
{
"id": 3,
"name": "Faizal"
}
]
Web Server - Simple Routing
const http = require("http");
const fs = require("fs");
const { getRoute } = require("./router");
const hostname = "127.0.0.1";
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
const route = getRoute(req, res);
const content =
fs.readFileSync(`${__dirname}/${route}.html`);
res.end(content);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// file router.js
const getRoute = (req, res) => {
let route = "";
switch (req.url) {
case "/":
route = "index";
break;
case "/contact":
route = "contact";
break;
case "/about":
route = "about";
break;
default:
res.statusCode = 404;
route = "404";
break;
}
return route;
};
module.exports.getRoute = getRoute;
NPM
Node Package Manager (NPM)
● npm stands for Node Package Manager
● From the website: Essential JavaScript development tools that help you go
to market faster and build powerful applications using modern open
source code. (npmjs.org)
● You can install, share and manage node.js packages.
● Basic Commands: install, init, etc…
● Ship with Node.js
node -v
npm -v
npm init
npm install
Express.js
What is Express.js?
● Express is a minimal and flexible Node.js web application framework that
provides a robust set of features for web and mobile applications.
Why Using Express.js?
● Fast!
● Simple
● Flexible
● Quick and Easy
● Routing
● Middleware
● View Engine
Express.js - Hello World
const express = require("express");
const app = express();
const port = 3000;
app.get("/", (req, res) => res.send("Hello World!"));
app.listen(port, () => console.log(`Example app listening on port
${port}!`));
Express.js - Routing
● Routing refers to determining how an
application responds to a client request
to a particular endpoint, which is a URI
(or path) and a specific HTTP request
method (GET, POST, and so on).
● Each route can have one or more
handler functions, which are executed
when the route is matched.
app.METHOD(PATH, HANDLER)
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.post("/", (req, res) => {
res.send("Got a POST request");
});
app.put("/user", (req, res) => {
res.send("Got a PUT request at
/user");
});
app.delete("/user", (req, res) => {
res.send("Got a DELETE request at
/user");
});
Express.js - Middleware
● Middleware functions are functions
that have access to the request
object (req), the response object
(res), and the next function in the
application’s request-response
cycle.
● The next function is a function in
the Express router which, when
invoked, executes the middleware
succeeding the current
middleware.
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 in the
stack.
Express.js - Writing Middleware
// middleware declaration
const myLogger = function(req, res, next) {
console.log("LOGGED");
next();
};
// using middleware
app.use(myLogger);
Express.js - Writing Middleware
// application-level middleware
app.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
// error handling middleware
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
Express.js - Writing Middleware
// route-level middleware
const app = express()
const router = express.Router()
// a middleware function with no mount path.
// This code is executed for every request to the router
router.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
router.get('/somepath', function (req, res, next) {
res.send('Hello!')
})
Express.js - Simple API
app.get("/", (req, res) => {
res.json({
status: true,
message: "Hello World"
});
});
// Live Coding
Build Simple App
with Express.js
What app?
● App to monitor stock of products
● Basic CRUD with Node.js
● API-based app
Build App - Prepare
● Install Express Generator npm i -g express-generator
● Create new folder and cd into it
● Run express to generate a scaffold
● Install the dependencies by running npm install
● Run the app: npm start
● Open app at http://localhost:3000
● Install nodemon
Build App - Setup Routes
router.get("/", function(req, res, next) {
res.send("Show all products");
});
router.post("/", function(req, res, next) {
res.send("Create new product");
});
router.get("/:id", function(req, res, next) {
res.send("Get product detail");
});
router.put("/:id", function(req, res, next) {
res.send("Update product");
});
router.delete("/:id", function(req, res, next) {
res.send("Delete product");
});
Build App - Sequelize and MySQL
Install sequelize, sequelize-cli and mysql
npm i sequelize sequelize-cli mysql2 --save
Init sequelize by running
npx sequelize-cli init
Create migration and model
npx sequelize-cli model:generate --name Product
--attributes=name:string,description:text,price:integer,st
ock:integer
Build App - Migration
Create database named fun_nodejs
Setup database configuration on config/database.json file
Run migration by running npx sequelize-cli db:migrate
Open MySQL GUI and see if the products table was created
Try undo migration by running npx sequelize-cli db:migrate:undo
Open MySQL GUI again and now the products table was deleted
Run migration again and do not undo for now
Build App - Seeders
Theory: seeders used for creating dummy data
---
Create seeder for product by running:
npx sequelize-cli seed:generate --name product-seeder
Follow my live coding :D
Run the seeder by running:
npx sequelize-cli db:seed:all
Now check the database and view products data
Build App - Implement API: Get All Products
const model = require("../models");
router.get("/", async function(req, res, next) {
const products = await model.Product.findAll();
res.json({
data: products
});
});
Build App - Implement API: Create new Product
router.post("/", async function(req, res, next) {
const data = req.body;
const product = await model.Product.create(data);
res.json({
data: product
});
});
Build App - Implement API: View Product Detail
router.get("/:id", async function(req, res, next) {
const id = req.params.id;
const product = await model.Product.findOne({ id });
res.json({
data: product
});
});
Build App - Implement API: Update Product
router.put("/:id", async function(req, res, next) {
const id = req.params.id;
const data = req.body;
const isUpdated = await model.Product.update(data, {
where: { id }
});
res.json({
data,
message: isUpdated ? "Product updated!" : "Product not
found"
});
});
Build App - Implement API: Delete Product
router.delete("/:id", async function(req, res, next) {
const id = req.params.id;
const isDeleted = await model.Product.destroy({
where: { id }
});
res.json({
message: isDeleted ? "Product deleted!" : "Product not
found"
});
});
Build App - Service Pattern
const Product = require("../models").Product;
module.exports = {
getAll() {
return Product.findAll();
},
create(data) {
return Product.create(data);
},
findById(id) {
return Product.findOne({ id });
},
update(id, data) {
return Product.update(data, {
where: { id }
});
},
};
Deploying
Node.js App
Deployment - Service
● Heroku
● AWS
● Your own Server (VPS)
Get Slides
http://bit.ly/fundamentalnodejs
Question? Thanks!
Please...
Ad

More Related Content

What's hot (20)

Understanding the Node.js Platform
Understanding the Node.js PlatformUnderstanding the Node.js Platform
Understanding the Node.js Platform
Domenic Denicola
 
Hybrid apps - Your own mini Cordova
Hybrid apps - Your own mini CordovaHybrid apps - Your own mini Cordova
Hybrid apps - Your own mini Cordova
Ayman Mahfouz
 
From Node.js to Design Patterns
From Node.js to Design Patterns From Node.js to Design Patterns
From Node.js to Design Patterns
Luciano Mammino
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Guillaume Laforge
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
Apaichon Punopas
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
Arvind Devaraj
 
(C)NodeJS
(C)NodeJS(C)NodeJS
(C)NodeJS
Jackson Tian
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
Javier Abadía
 
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
Alessandro Molina
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
Kamal Hussain
 
Learning WebGLで学ぶWebGL入門
Learning WebGLで学ぶWebGL入門Learning WebGLで学ぶWebGL入門
Learning WebGLで学ぶWebGL入門
nakamura001
 
Node ppt
Node pptNode ppt
Node ppt
Tamil Selvan R S
 
SWT Tech Sharing: Node.js + Redis
SWT Tech Sharing: Node.js + RedisSWT Tech Sharing: Node.js + Redis
SWT Tech Sharing: Node.js + Redis
Infinity Levels Studio
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
Akshay Mathur
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
Domenic Denicola
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
Jeado Ko
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open web
pjcozzi
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
Fabien Vauchelles
 
Node.js for enterprise - JS Conference
Node.js for enterprise - JS ConferenceNode.js for enterprise - JS Conference
Node.js for enterprise - JS Conference
Timur Shemsedinov
 
Understanding the Node.js Platform
Understanding the Node.js PlatformUnderstanding the Node.js Platform
Understanding the Node.js Platform
Domenic Denicola
 
Hybrid apps - Your own mini Cordova
Hybrid apps - Your own mini CordovaHybrid apps - Your own mini Cordova
Hybrid apps - Your own mini Cordova
Ayman Mahfouz
 
From Node.js to Design Patterns
From Node.js to Design Patterns From Node.js to Design Patterns
From Node.js to Design Patterns
Luciano Mammino
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Guillaume Laforge
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
Javier Abadía
 
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
Alessandro Molina
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
Kamal Hussain
 
Learning WebGLで学ぶWebGL入門
Learning WebGLで学ぶWebGL入門Learning WebGLで学ぶWebGL入門
Learning WebGLで学ぶWebGL入門
nakamura001
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
Akshay Mathur
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
Jeado Ko
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open web
pjcozzi
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
Fabien Vauchelles
 
Node.js for enterprise - JS Conference
Node.js for enterprise - JS ConferenceNode.js for enterprise - JS Conference
Node.js for enterprise - JS Conference
Timur Shemsedinov
 

Similar to Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, Warsono) (20)

NodeJS
NodeJSNodeJS
NodeJS
Alok Guha
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathon
Luciano Mammino
 
Nodejs
NodejsNodejs
Nodejs
Mahmoud Atef Abdelsamie
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
Ben Hall
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Tech friday 22.01.2016
Tech friday 22.01.2016Tech friday 22.01.2016
Tech friday 22.01.2016
Poutapilvi Web Design
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
Steven Beeckman
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
Mike Brevoort
 
Implementing new WebAPIs
Implementing new WebAPIsImplementing new WebAPIs
Implementing new WebAPIs
Julian Viereck
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
François Sarradin
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
Budh Ram Gurung
 
HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?
Ankara JUG
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
Lucio Grenzi
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
Yoann Gotthilf
 
A More Flash Like Web?
A More Flash Like Web?A More Flash Like Web?
A More Flash Like Web?
Murat Can ALPAY
 
node.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Servernode.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Server
David Ruiz
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathon
Luciano Mammino
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
Ben Hall
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
Mike Brevoort
 
Implementing new WebAPIs
Implementing new WebAPIsImplementing new WebAPIs
Implementing new WebAPIs
Julian Viereck
 
HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?
Ankara JUG
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
Lucio Grenzi
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
Yoann Gotthilf
 
node.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Servernode.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Server
David Ruiz
 
Ad

More from GITS Indonesia (10)

GITS Webinar: How to Build UI/UX Portfolio that Stand Out
GITS Webinar: How to Build UI/UX Portfolio that Stand Out GITS Webinar: How to Build UI/UX Portfolio that Stand Out
GITS Webinar: How to Build UI/UX Portfolio that Stand Out
GITS Indonesia
 
GITS Webinar: Implementasi REST API di iOS Menggunakan Alamofire dan SwiftyJSON
GITS Webinar: Implementasi REST API di iOS Menggunakan Alamofire dan SwiftyJSONGITS Webinar: Implementasi REST API di iOS Menggunakan Alamofire dan SwiftyJSON
GITS Webinar: Implementasi REST API di iOS Menggunakan Alamofire dan SwiftyJSON
GITS Indonesia
 
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
GITS Indonesia
 
GITS Class #21 How to Build Your Dream Team to Achieve the Target
GITS Class #21 How to Build Your Dream Team to Achieve the TargetGITS Class #21 How to Build Your Dream Team to Achieve the Target
GITS Class #21 How to Build Your Dream Team to Achieve the Target
GITS Indonesia
 
GITS Class #20: Building A Fast and Responsive UI in React Native
GITS Class #20: Building A Fast and Responsive UI in React NativeGITS Class #20: Building A Fast and Responsive UI in React Native
GITS Class #20: Building A Fast and Responsive UI in React Native
GITS Indonesia
 
GITS Class #19: Build Large Scale Vue.js Apps with Vuex
GITS Class #19: Build Large Scale Vue.js Apps with VuexGITS Class #19: Build Large Scale Vue.js Apps with Vuex
GITS Class #19: Build Large Scale Vue.js Apps with Vuex
GITS Indonesia
 
GITS Class #17: Coding Multiple Apps with Flutter
GITS Class #17: Coding Multiple Apps with FlutterGITS Class #17: Coding Multiple Apps with Flutter
GITS Class #17: Coding Multiple Apps with Flutter
GITS Indonesia
 
GITS Class #16: CI/CD (Continuous Integration & Continuous Deployment) with G...
GITS Class #16: CI/CD (Continuous Integration & Continuous Deployment) with G...GITS Class #16: CI/CD (Continuous Integration & Continuous Deployment) with G...
GITS Class #16: CI/CD (Continuous Integration & Continuous Deployment) with G...
GITS Indonesia
 
GITS Class #12: iOS & Android Component Principles bersama Ajie Arga dan Radh...
GITS Class #12: iOS & Android Component Principles bersama Ajie Arga dan Radh...GITS Class #12: iOS & Android Component Principles bersama Ajie Arga dan Radh...
GITS Class #12: iOS & Android Component Principles bersama Ajie Arga dan Radh...
GITS Indonesia
 
GITS Class #11: Android Architecture Component bersama Derayan Bima (Android ...
GITS Class #11: Android Architecture Component bersama Derayan Bima (Android ...GITS Class #11: Android Architecture Component bersama Derayan Bima (Android ...
GITS Class #11: Android Architecture Component bersama Derayan Bima (Android ...
GITS Indonesia
 
GITS Webinar: How to Build UI/UX Portfolio that Stand Out
GITS Webinar: How to Build UI/UX Portfolio that Stand Out GITS Webinar: How to Build UI/UX Portfolio that Stand Out
GITS Webinar: How to Build UI/UX Portfolio that Stand Out
GITS Indonesia
 
GITS Webinar: Implementasi REST API di iOS Menggunakan Alamofire dan SwiftyJSON
GITS Webinar: Implementasi REST API di iOS Menggunakan Alamofire dan SwiftyJSONGITS Webinar: Implementasi REST API di iOS Menggunakan Alamofire dan SwiftyJSON
GITS Webinar: Implementasi REST API di iOS Menggunakan Alamofire dan SwiftyJSON
GITS Indonesia
 
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
GITS Indonesia
 
GITS Class #21 How to Build Your Dream Team to Achieve the Target
GITS Class #21 How to Build Your Dream Team to Achieve the TargetGITS Class #21 How to Build Your Dream Team to Achieve the Target
GITS Class #21 How to Build Your Dream Team to Achieve the Target
GITS Indonesia
 
GITS Class #20: Building A Fast and Responsive UI in React Native
GITS Class #20: Building A Fast and Responsive UI in React NativeGITS Class #20: Building A Fast and Responsive UI in React Native
GITS Class #20: Building A Fast and Responsive UI in React Native
GITS Indonesia
 
GITS Class #19: Build Large Scale Vue.js Apps with Vuex
GITS Class #19: Build Large Scale Vue.js Apps with VuexGITS Class #19: Build Large Scale Vue.js Apps with Vuex
GITS Class #19: Build Large Scale Vue.js Apps with Vuex
GITS Indonesia
 
GITS Class #17: Coding Multiple Apps with Flutter
GITS Class #17: Coding Multiple Apps with FlutterGITS Class #17: Coding Multiple Apps with Flutter
GITS Class #17: Coding Multiple Apps with Flutter
GITS Indonesia
 
GITS Class #16: CI/CD (Continuous Integration & Continuous Deployment) with G...
GITS Class #16: CI/CD (Continuous Integration & Continuous Deployment) with G...GITS Class #16: CI/CD (Continuous Integration & Continuous Deployment) with G...
GITS Class #16: CI/CD (Continuous Integration & Continuous Deployment) with G...
GITS Indonesia
 
GITS Class #12: iOS & Android Component Principles bersama Ajie Arga dan Radh...
GITS Class #12: iOS & Android Component Principles bersama Ajie Arga dan Radh...GITS Class #12: iOS & Android Component Principles bersama Ajie Arga dan Radh...
GITS Class #12: iOS & Android Component Principles bersama Ajie Arga dan Radh...
GITS Indonesia
 
GITS Class #11: Android Architecture Component bersama Derayan Bima (Android ...
GITS Class #11: Android Architecture Component bersama Derayan Bima (Android ...GITS Class #11: Android Architecture Component bersama Derayan Bima (Android ...
GITS Class #11: Android Architecture Component bersama Derayan Bima (Android ...
GITS Indonesia
 
Ad

Recently uploaded (20)

Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 

Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, Warsono)

  • 2. Current Position: Frontend Web Developer at GITS Indonesia Formerly: Backend Web Developer at Panenmaya Digital Email: [email protected] Website: https://warsono.id Social Media: Github: /gravitano Linkedin: /in/gravitano Medium: @gravitano Instagram: /warsonoid Warsono Muhamad Faizal Frontend Web Developer
  • 3. Agenda ● Introduction to Node.js ● Asynchronous Programming ● Basic JavaScript ● Web Server with Node.js ● Express.js ● Build App with Express.js
  • 5. What is Node.js? ● Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. ● It was created by Ryan Dahl in 2009 ● It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. ● It’s an asynchronous event-driven JavaScript runtime, which is designed to build scalable network applications. ● It can handle many concurrent connections at a time, where when connection request are made concurrently for each connection a callback is fired. ● In a simple words, Node.js is “server-side JavaScript”
  • 6. Why Node.js? ● It is asynchronous (non-blocking) ● Very fast! It is much faster than Ruby, Python, or Perl. ● Ability to handle thousands of concurrent connections with minimal overhead on a single process ● Single-threaded but highly scalable ● Node.js is very reliable especially for making real-time applications ● Single programming language for client and server
  • 7. Who’s using Node.js? ● GoDaddy ● Groupon ● IBM ● LinkedIn ● Microsoft ● Netflix ● PayPal ● Walmart ● More...
  • 8. Node.js Frameworks ● Express: It provides one of the most simple yet powerful ways to create a web server. Its minimalist approach, unopinionated, focused on the core features of a server, is key to its success. ● AdonisJs: A full-stack framework highly focused on developer ergonomics, stability, and confidence. Adonis is one of the fastest Node.js web frameworks. ● NestJS: A TypeScript based progressive Node.js framework for building enterprise-grade efficient, reliable and scalable server-side applications. ● Socket.io: A real-time communication engine to build network applications.
  • 10. Synchronous JavaScript ● JavaScript code runs on a single thread (can do 1 thing at a time) ● Synchronous code waits for 1 action to complete before moving on to the next
  • 11. Asynchronous JavaScript ● An asynchronous model allows multiple things to happen at the same time. ● When you start an action, your program continues to run.
  • 14. Warning! ● Program for Node.js are written in JavaScript ● There is no DOM implementation provided by Node.js, i.e. you can not do this: document.getElementById(‘element’); window.alert(‘Hello’);
  • 16. Basic JavaScript - Console var myString = "Hello World"; var myObject = { hello: "World" }; console.log(myString); // alias for console.log console.info(myObject); console.warn("Warning!"); // Displays data as a table. console.table([{ a: 1, b: "Y" }, { a: "Z", b: 2 }]); // Starts a timer you can use // to track how long an operation takes console.time("benchmark"); for (var i = 0; i < 100; i++) {} console.timeEnd("benchmark"); console.trace("Show me");
  • 17. Basic JavaScript - Variable : Var/Let/Const var hello = "Hello"; let world = "World"; const helloWorld = "Hello" + " " + world; const myString = new String("This is a string"); var hello = "Halo"; let world = "Dunia"; // SyntaxError: Identifier 'world' has already been declared const myString = "Ini sebuah string"; // SyntaxError: Identifier 'myString' has already been declared console.log(hello, world, myString);
  • 18. Basic JavaScript - Boolean ● Truthy ○ 1 ○ -1 ○ '1' ○ 'abc' ○ ' ' ○ true ○ {} ○ [] ○ Infinity / -Infinity ○ function(){} / () => {} ● Falsy ○ false ○ '' ○ 0 ○ null ○ undefined ○ NaN
  • 19. Basic JavaScript - Conditional const price = 1000; if (price <= 1000) { console.log("Small"); } else if (price > 1000 && price < 5000) { console.log("Medium"); } else { console.log("Large"); } const status = "pending"; switch (status) { case "pending": console.log("Pending"); break; case "approved": console.log("Approved"); break; default: console.log("Unknown"); break; }
  • 20. Basic JavaScript - Looping // loops through a block of code a number of times for (let i = 0; i < 5; i++) { console.log("The number is " + i); } // loops through the properties of an object const person = { firstName: "John", lastName: "Doe", age: 25 }; for (key in person) { console.log(key, person[key]); } // loops through the values of an iterable object var cars = ["BMW", "Volvo", "Mini"]; for (car of cars) { console.log(car); } // loops through a block of code while a specified condition is true let i = 0; while (i < 10) { console.log("The i number is " + i); i++; } // also loops through a block of code while a specified condition is true let j = 0; do { console.log("The j number is " + j); j++; } while (j < 10);
  • 21. Basic JavaScript - Function function showMessage() { console.log("Weather information"); } const toCelsius = function(fahrenheit) { return (5 / 9) * (fahrenheit - 32); }; const showWeatherInfo = function(fahrenheit) { console.log("Info: ", toCelsius(fahrenheit)); }; // arrow function const myFunction = () => 43; const myFunction2 = text => { return text; }; const myFunction3 = (param1, param2) => { return `${param1}, ${param2}`; }; // calling function showMessage(); console.log(toCelsius(42)); showWeatherInfo(70);
  • 22. Basic JavaScript - Module // file: module/math.js const add = (x, y) => x + x; const subtract = (x, y) => x - y; module.exports.add = add; exports.subtract = subtract; // file: module/app.js const math = require("./math"); // es6 const { add, subtract } = require("./math"); console.log(math.add(10, 2)); // 20 console.log(math.subtract(10, 2)); // 8 console.log(add(10, 2)); // 20 console.log(subtract(10, 2)); // 8
  • 23. Basic JavaScript - Module : Export as object const add = (x, y) => x + x; const subtract = (x, y) => x - y; module.exports = { add: add, subtract: subtract }; module.exports = { add, // es6 shorthand for add: add subtract };
  • 24. Basic JavaScript - Module : Default Export // file: module/add.js const add = (x, y) => x + x; module.exports = add; // file: module/app3.js const add = require("./add"); console.log(add(10, 2)); // 20
  • 25. Basic JavaScript - Callback ● A callback is a function that is to be executed after another function has finished executing — hence the name ‘call back’. ● In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions. ● Functions that do this are called higher-order functions. ● Any function that is passed as an argument is called a callback function. setTimeout(function() { console.log(1); }, 500); $('#my_button').on('click', function(e) { console.log('Ouhh aku di klik!'); })
  • 26. Basic JavaScript - Promise ● The Promise object is used for deferred and asynchronous computations. ● A Promise represents an operation that hasn't completed yet, but is expected in the future.
  • 27. Basic JavaScript - Promise : Example 1 const fs = require("fs"); // contoh promise untuk async const promiseAsync = new Promise((resolve, reject) => { fs.readFile(__dirname + "/hello.txt", "utf8", (err, res) => { if (err) reject(err); resolve(res); }); }); promiseAsync .then(res => console.log("Hasil Async: ", res)) .catch(err => console.log("error", err)); // contoh promise untuk sync const promiseSync = new Promise(resolve => { resolve("Hello Sync"); }); promiseSync.then(res => console.log("Hasil Sync: ", res));
  • 28. Basic JavaScript - Promise : Example 2 const fs = require("fs"); const getData = filename => { return new Promise((resolve, reject) => { fs.readFile(__dirname + "/" + filename, "utf8", (err, res) => { if (err) reject(err); resolve(res); }); }); }; getData("data.json") .then(result => { console.log("result", result); console.log(typeof result); return JSON.parse(result); }) .then(result2 => { console.log("result 2", result2); console.log(typeof result2); }) .catch(err => { console.log("Whoops! Something went wrong..."); console.error(err); });
  • 29. Basic JavaScript - Promise : Example 3 const promise1 = new Promise(resolve => { setTimeout(() => { resolve(1); }, 5000); }); const promise2 = new Promise(resolve => { setTimeout(() => { resolve(2); }, 1000); }); Promise.race([promise1, promise2]).then(res => { console.log(res); }); Promise.all([promise1, promise2]).then(res => { console.log(res); });
  • 30. Basic JavaScript - Async/Await ● Async and Await are extensions of promises ● Async functions enable us to write promise based code as if it were synchronous, but without blocking the execution thread. ● Async functions will always return a value ● Using async simply implies that a promise will be returned, and if a promise is not returned, JavaScript automatically wraps it in a resolved promise with its value. async function firstAsync() { return 27; } firstAsync().then(alert); // 27
  • 31. Basic JavaScript - Async/Await : Example async function firstAsync() { let promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Now it's done!"), 500); }); // wait until the promise returns us a value let result = await promise; // "Now it's done!" console.log("result:", result); } firstAsync();
  • 32. Basic JavaScript - Async/Await Things to remember when using Async Await ● We can’t use the await keyword inside of regular functions. ● Async Await makes execution sequential // error function firstAsync() { let promise = Promise.resolve(10); let result = await promise; // Syntax error } async function sequence() { await promise1(50); // Wait 50ms… await promise2(50); // …then wait another 50ms. return "done!"; }
  • 34. Web Server - Hello World Example const http = require("http"); const hostname = "127.0.0.1"; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader("Content-Type", "text/plain"); res.end("Hello World"); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
  • 35. Web Server - Render HTML const http = require("http"); const fs = require("fs"); const hostname = "127.0.0.1"; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader("Content-Type", "text/html"); const content = fs.readFileSync(__dirname + "/index.html"); res.end(content); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
  • 36. const http = require("http"); const data = require("./data.json"); const hostname = "127.0.0.1"; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader("Content-Type", "application/json"); const content = JSON.stringify(data); res.end(content); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); Web Server - Render JSON [ { "id": 1, "name": "Warsono" }, { "id": 2, "name": "Andy" }, { "id": 3, "name": "Faizal" } ]
  • 37. Web Server - Simple Routing const http = require("http"); const fs = require("fs"); const { getRoute } = require("./router"); const hostname = "127.0.0.1"; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader("Content-Type", "text/html"); const route = getRoute(req, res); const content = fs.readFileSync(`${__dirname}/${route}.html`); res.end(content); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); // file router.js const getRoute = (req, res) => { let route = ""; switch (req.url) { case "/": route = "index"; break; case "/contact": route = "contact"; break; case "/about": route = "about"; break; default: res.statusCode = 404; route = "404"; break; } return route; }; module.exports.getRoute = getRoute;
  • 38. NPM
  • 39. Node Package Manager (NPM) ● npm stands for Node Package Manager ● From the website: Essential JavaScript development tools that help you go to market faster and build powerful applications using modern open source code. (npmjs.org) ● You can install, share and manage node.js packages. ● Basic Commands: install, init, etc… ● Ship with Node.js node -v npm -v npm init npm install
  • 41. What is Express.js? ● Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
  • 42. Why Using Express.js? ● Fast! ● Simple ● Flexible ● Quick and Easy ● Routing ● Middleware ● View Engine
  • 43. Express.js - Hello World const express = require("express"); const app = express(); const port = 3000; app.get("/", (req, res) => res.send("Hello World!")); app.listen(port, () => console.log(`Example app listening on port ${port}!`));
  • 44. Express.js - Routing ● Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). ● Each route can have one or more handler functions, which are executed when the route is matched. app.METHOD(PATH, HANDLER) app.get("/", (req, res) => { res.send("Hello World!"); }); app.post("/", (req, res) => { res.send("Got a POST request"); }); app.put("/user", (req, res) => { res.send("Got a PUT request at /user"); }); app.delete("/user", (req, res) => { res.send("Got a DELETE request at /user"); });
  • 45. Express.js - Middleware ● Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. ● The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. 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 in the stack.
  • 46. Express.js - Writing Middleware // middleware declaration const myLogger = function(req, res, next) { console.log("LOGGED"); next(); }; // using middleware app.use(myLogger);
  • 47. Express.js - Writing Middleware // application-level middleware app.use(function (req, res, next) { console.log('Time:', Date.now()) next() }) // error handling middleware app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!') })
  • 48. Express.js - Writing Middleware // route-level middleware const app = express() const router = express.Router() // a middleware function with no mount path. // This code is executed for every request to the router router.use(function (req, res, next) { console.log('Time:', Date.now()) next() }) router.get('/somepath', function (req, res, next) { res.send('Hello!') })
  • 49. Express.js - Simple API app.get("/", (req, res) => { res.json({ status: true, message: "Hello World" }); }); // Live Coding
  • 50. Build Simple App with Express.js
  • 51. What app? ● App to monitor stock of products ● Basic CRUD with Node.js ● API-based app
  • 52. Build App - Prepare ● Install Express Generator npm i -g express-generator ● Create new folder and cd into it ● Run express to generate a scaffold ● Install the dependencies by running npm install ● Run the app: npm start ● Open app at http://localhost:3000 ● Install nodemon
  • 53. Build App - Setup Routes router.get("/", function(req, res, next) { res.send("Show all products"); }); router.post("/", function(req, res, next) { res.send("Create new product"); }); router.get("/:id", function(req, res, next) { res.send("Get product detail"); }); router.put("/:id", function(req, res, next) { res.send("Update product"); }); router.delete("/:id", function(req, res, next) { res.send("Delete product"); });
  • 54. Build App - Sequelize and MySQL Install sequelize, sequelize-cli and mysql npm i sequelize sequelize-cli mysql2 --save Init sequelize by running npx sequelize-cli init Create migration and model npx sequelize-cli model:generate --name Product --attributes=name:string,description:text,price:integer,st ock:integer
  • 55. Build App - Migration Create database named fun_nodejs Setup database configuration on config/database.json file Run migration by running npx sequelize-cli db:migrate Open MySQL GUI and see if the products table was created Try undo migration by running npx sequelize-cli db:migrate:undo Open MySQL GUI again and now the products table was deleted Run migration again and do not undo for now
  • 56. Build App - Seeders Theory: seeders used for creating dummy data --- Create seeder for product by running: npx sequelize-cli seed:generate --name product-seeder Follow my live coding :D Run the seeder by running: npx sequelize-cli db:seed:all Now check the database and view products data
  • 57. Build App - Implement API: Get All Products const model = require("../models"); router.get("/", async function(req, res, next) { const products = await model.Product.findAll(); res.json({ data: products }); });
  • 58. Build App - Implement API: Create new Product router.post("/", async function(req, res, next) { const data = req.body; const product = await model.Product.create(data); res.json({ data: product }); });
  • 59. Build App - Implement API: View Product Detail router.get("/:id", async function(req, res, next) { const id = req.params.id; const product = await model.Product.findOne({ id }); res.json({ data: product }); });
  • 60. Build App - Implement API: Update Product router.put("/:id", async function(req, res, next) { const id = req.params.id; const data = req.body; const isUpdated = await model.Product.update(data, { where: { id } }); res.json({ data, message: isUpdated ? "Product updated!" : "Product not found" }); });
  • 61. Build App - Implement API: Delete Product router.delete("/:id", async function(req, res, next) { const id = req.params.id; const isDeleted = await model.Product.destroy({ where: { id } }); res.json({ message: isDeleted ? "Product deleted!" : "Product not found" }); });
  • 62. Build App - Service Pattern const Product = require("../models").Product; module.exports = { getAll() { return Product.findAll(); }, create(data) { return Product.create(data); }, findById(id) { return Product.findOne({ id }); }, update(id, data) { return Product.update(data, { where: { id } }); }, };
  • 64. Deployment - Service ● Heroku ● AWS ● Your own Server (VPS)