Salah satu front-end developer GITS Indonesia, Warsono, mengisi workshop di universitas, mengenai Vue.js.
Ikuti kami di kanal berikut, agar tidak ketinggalan acara seru:
Instagram: @gitsindonesia
LinkedIn: GITS Indonesia
Website: gits.id
2. 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
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);
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);
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.
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!";
}
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.
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.
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!')
})
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
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
});
});