SlideShare a Scribd company logo
1 of 37
Download to read offline
NODE JS
JavaScript on the server
Node Course Guide
This guide is designed to supplement the
Introduction to Node js for beginners + game project Course
It includes source code that follows the lessons of the course. One of the best ways to learn is to try the code out
for yourself. Thanks for taking the course, if you have any questions or need clarification on the content please
let me know in the Q&A section.
Happy Coding …..
What is Node and how does it work
JavaScript on the server.
● run JavaScript on the server
● open source server environment
● can connect to a database
● Create, open, read write, delete files on
your server
● Generate page content
Node.js runs single-threaded, asynchronously
programming, which is very memory efficient.
Server-side JavaScript
JavaScript uses browsers to run code on the
frontend.
On the backend needs to be interpreted
(executed). Node.js uses Google’s V8 VM which
is the same runtime environment the Chrome
uses.
Node.js comes with many useful modules -
saves from writing from scratch.
Node is runtime environment and a library
Node.js - Install
Node files have a js extension
Download and install node at https://nodejs.org
Terminal - for command line interface
Node package manager - share code and reuse
existing code. Faster development.
https://www.npmjs.com/
Install https://www.npmjs.com/get-npm
You will also need an editor - brackets.io
Windows Terminal
Windows - https://cmder.net/ or use the
command prompt terminal
Launch the Command Prompt - use the Run
window or press the Win + R keys on your
keyboard. Then, type cmd and press Enter.
List current directory of files - dir
Change directory to D drive - cd D:
Change directory down one level - cd..
Change directory to folder by name - cd folder
Make new folder - mkdir folderName
Get help - help
Mac Terminal
Open Terminal by pressing Command+Space or
select terminal in the applications list.
List current directory of files - ls
Change directory to D drive - cd D:
Change directory down one level - cd..
Change directory to folder by name - cd folder
Make new folder - mkdir folderName
Get help - help
Command Line Launch
One node is installed check to see version
installed. Type node -v
Open your editor and create a js file that
contains console.log('Hello World'); save
it as test.js
In the terminal type node test.js and watch
for a result. What gets returned?
NPM - check if its installed npm -v latest
version install npm install npm@latest -g
First Node File
One node is installed check to see version
installed. Type node -v
Open your editor and create a js file that
contains console.log('Hello World'); save
it as test.js
In the terminal type node test.js and watch
for a result. What gets returned?
Node file in the browser
To run the file in a browser you need to
serve the web pages. HTTP server
URL where the content will render. Map
requests and show pages.
Request handlers on the server side to
show page.
Viewing logic to send content to users
browser.
NODE can do all this…
First Node HTTP File
Require directive - loads the http module and stores the
returned HTTP instance as a variable.
Create Server method. http.createServer()
Bind it to port 8080 .listen(8080)
Write to the response writeHead method. Set status code
to 200 success okay and specify content type. text/plain
Add body with content end method.
Save the file as app.js open the terminal type node app.js
then open your browser to http://localhost:8080/
var http = require('http');
http.createServer(function (request, response)
{
response.writeHead(200, {'Content-Type':
'text/plain'});
response.end('Hello World!');
}).listen(8080);
Try the Code
var http = require("http");
http.createServer(function (request, response) {
response.writeHead(200, {
"Content-Type": "text/plain"
});
response.write("Hello World");
response.end();
}).listen(8080);
Node How it works
Node uses a single process - where as
other languages like PHP would open a
new process for every HTTP request.
Callback is an asynchronous equivalent
for a function. (event-driven,
asynchronous callbacks allow for moving
to the next line.)
function message(greeting, callback) {
console.log(`${greeting}.`);
callback(); // afterwards gets invoked here
}
function afterwards(){
console.log('GoodBye!');
}
message('Hello', afterwards);
Node modules
Modules in node are like JavaScript libraries. Pre
Written code that you can pull into your project
and use.
Node.js has a set of built-in modules which you
can use without any additional installation.
To include a module, use the require() function
with the name of the module.
var http = require('http');
Module
A module is a JavaScript library/file
that you can import into other code
using Node's require() function
https://www.npmjs.com/
https://www.npmjs.com/search?q=tw
itter
Create a module
Allows you to easily reuse code. //file called module.js
exports.greeting = "hello world";
//file called testmod.js
const output = require('./module.js')
console.log(output.greeting);
Node web server
const http = require("http"); //loads module called http
function req(request, response) { //callback function
response.writeHead(200, { //sends HTTP status 200
"Content-Type": "text/plain"
});
response.write("Hello World"); //page content response body
response.end(); //finish the response.
}
http.createServer(req).listen(8080); //method creates an HTTP server
console.log('Server started');
Files on your server
Read index1.html to your web browser.
const http = require('http');
const fs = require('fs');
function req(request, response) {
fs.readFile('index1.html', function (error, data) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.write(data);
response.end();
})
}
http.createServer(req).listen(8080);
console.log('Server started');
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>Welcome</h1>
<p>I enjoy JavaScript.</p>
</body>
</html>
Node URL pathname request
const http = require('http');
const url = require('url');
function onRequest(request, response) {
const base = url.parse(request.url);
const pathname = base.pathname;
console.log(pathname + ' received.');
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.write('Welcome');
response.end();
}
http.createServer(onRequest).listen(8080);
console.log('Started');
http://localhost:8080/foo
Default is to look for favicon on every page.
Node Routing const http = require('http');
const url = require('url');
const fs = require('fs');
function onRequest(request, response) {
const base = url.parse(request.url);
const fileName = '.' + base.pathname;
fs.readFile(fileName, function (error, data) {
if (error) {
response.writeHead(404, {
'Content-Type': 'text/html'
});
return response.end('<h1>Not Found</h1>');
}
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.write(data);
return response.end();
})
}
http.createServer(onRequest).listen(8080);
console.log('Started');
Create some pages on your directory. Load them in
your browser.
File Write and Read const fs = require('fs');
fs.readFile('./db.json', 'utf-8', function (err, data) {
const d = JSON.parse(data); //data from db.json
console.log(d.message);
})
fs.readdir('./', function (err, data) {
console.log(data); // all directories from folder
})
const temp = {
greeting: 'Welcome to Node' //js object
}
fs.writeFile('db1.json', JSON.stringify(temp), function (error) {
//stringify to JSON
console.log('file created');
})
Node makes it easy to write and read files from your
computer. You can also read directories.
readFile use utf-8 as the character code
readdir - to read the directory file names
writeFile - to write to or create a file.
{"message":"Hello World"}
Loading Packages NPM
Popular package called lodash
https://www.npmjs.com/package/lodash
npm install lodash
● Installs a new folder with all dependant files.
● Warnings if no package.json which lists dependant
packages
package.json - Specifics of npm's package.json handling. At
the heart of node system all metadata for the project making it
easier to package and redistribute.
You can create a package.json file npm init
Answer the questions to complete
Short format is npm init --yes
Lodash Quick
https://lodash.com/ - https://lodash.com/docs/4.17.11
First setup Lodash if you haven’t already.
npm init - to create package.json file in folder
npm install lodash - to install package
-g to install current package as a global package
(npm i -g npm) shorthand i is for install then last parameter is
the package name.
npm install - will install all modules listed as dependencies in
package.json .
const _ = require('lodash');
let randomNum1 = _.random(10); // 0-10 random number
let randomNum2 = _.random(1, 100); // 0-10 random number
console.log(randomNum1);
console.log(randomNum2);
let myArr = ['apple', 'orange', 'banana', 'blue berry', 'grape',
'cherry'];
let randomItem = _.sample(myArr);
console.log(randomItem);
console.log(myArr);
console.log(_.shuffle(myArr));
console.log(_.shuffle(myArr));
let counter = 0;
_.times(5, function () { //Loops 5 times
counter++;
console.log(counter);
})
let arr2 = _.map(myArr, function (item) {
console.log(item);
return item.toUpperCase();
})
console.log(arr2);
console.log(_.map(myArr, _.camelCase));
console.log(_.map(myArr, _.capitalize));
console.log(_.map(myArr, _.upperCase));
console.log(_.map(myArr, _.lowerCase));
//return items that start with
let arr3 = _.map(myArr, function (e) {
return _.startsWith(e, 'b');
})
console.log(arr3);
let arr4 = _.map(myArr, function (e) {
return _.endsWith(e, 'e');
})
console.log(arr4);
myArr.forEach(function (e) {
if (_.endsWith(e, 'e')) {
console.log(e);
}
});
Packages Express
Express is the most popular Node web
framework, and is the underlying library for a
number of other popular Node web frameworks.
Express is a minimal and flexible Node.js web
application framework that provides a robust set
of features for web and mobile applications.
https://expressjs.com/
npm install express --save
http://localhost:3000/
const express = require('express');
const app = express();
const port = 3000;
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.get('/about', function(req, res) {
res.send('About Page');
});
app.listen(port, function () {
return console.log("Port is ".concat(port, "!"));
});
Express static files
__dirname is the directory that will be used.
http://localhost:3000/index1.html
http://localhost:3000
const express = require('express');
const app = express();
const port = 3000;
app.use(express.static(__dirname)); // change directory to root
app.listen(port, function () {
return console.log("Port is "+port + ' '+ __dirname);
});
http://localhost:3000/2
http://localhost:3000
const express = require('express');
const app = express();
const port = 3000;
app.get('/', function (req, res) {
res.sendFile(__dirname +'/index1.html');
});
app.get('/2', function (req, res) {
res.sendFile(__dirname +'/index2.html');
});
app.listen(port, function () {
return console.log("Port is "+port + ' '+ __dirname);
});
NodeMon
Nodemon is a utility that will monitor for any
changes in your source and automatically restart
your server. Perfect for development.
npm install -g nodemon
https://nodemon.io/
Run it
nodemon app.js
** make some changes no more node restart
typing ;)
Get data
<button>Click</button>
<div class="output"></div>
<script>
const btn = document.querySelector('button');
const output = document.querySelector('.output');
btn.addEventListener('click', listUsers);
function listUsers() {
fetch('users').then(function (response) {
return response.json();
}).then(function (data) {
output.innerHTML = "Users<br>";
data.forEach(function (el) {
let div = document.createElement('div');
div.textContent = el.user + ' ' + el.pass;
output.appendChild(div);
})
});
}
</script>
const express = require('express');
const app = express();
app.use(express.static(__dirname));
const users = [{
user: 'Laurence',
pass: 'secret'
}, {
user: 'Jane',
pass: 'password'
}];
app.get('/users', function (req, res) {
res.send(users);
});
const server = app.listen(3000, function () {
console.log('server' + server.address().port);
});
Body-parser
Parse incoming request bodies in a middleware
before your handlers
npm install body-parser
https://www.npmjs.com/package/body-parser
Send data from the front end code form to the
backend.
<form id="myform" action="login" method="post">
<input type="text" name="user" value="User Name">
<input type="text" name="pass" value="Password"> </form>
<div class="btn">Click Me</div>
<script>
const btn = document.querySelector('.btn');
btn.addEventListener('click', function () {
const formData = new FormData(document.forms[0]);
const searchParams = new URLSearchParams();
for (const val of formData) {
console.log(val);
searchParams.append(val[0], val[1]);
}
fetch('/login', {
method: 'post'
, body: searchParams
}).then(function (response) {
return response.json()
}).then(function (data) {
return console.log(data);
})
})
</script>
Body-parser
Middleware to get data
const express = require('express');
const app = express();
const port = 3000;
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json()); // for parsing application/json
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile("index.html");
});
app.post('/login', function (req, res) {
let userName = req.body.user;
let password = req.body.pass;
console.log("UserName = " + userName + ", password = " +
password);
res.json({
status: true
});
});
app.listen(3000, function () {
console.log("PORT " + port);
})
Socket.io
https://socket.io/
const express = require('express');
const app = express();
const port = 3000;
const http = require('http').Server(app);
const socket = require('socket.io')(http);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendfile("index.html");
});
socket.on('connection', function (s) {
console.log('user ready');
})
const server = http.listen(port, function () {
console.log("Ready " + port);
})
<input name="user" type="text" value="Laurence">
<button class="btn">Roll</button>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io(); //initialization of socket connection
const btn = document.querySelector('.btn');
btn.addEventListener('click', function () {
})
</script>
Socket.io send message to users
https://socket.io/docs/emit-cheatsheet/
http://localhost:3000/players - list players
http://localhost:3000/ - join game
<div class="output"></div><input name="user" type="text"
value="Laurence"><button class="btn1">Join</button>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const output = document.querySelector('.output');
const btn1 = document.querySelector('.btn1');
const user = document.querySelector('input[name=user]');
btn1.addEventListener('click', function () {
var id = 'player_' + Math.floor(Date.now() * Math.random());
socket.emit('new player', id, user.value);
user.style.display = 'none';
btn1.style.display = 'none';
})
socket.on('players', listPlayers);
function listPlayers(players) {
output.innerHTML = 'Players<br>';
players.forEach(function (player) {
let div = document.createElement('div');
div.textContent = player.name;
output.appendChild(div);
})
}
</script>
index.html
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const http = require('http').Server(app);
const io = require('socket.io')(http);
let players = [];
const bodyParser = require('body-parser');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(__dirname + '/public'));
http.listen(port, function () {
console.log("Ready " + port);
})
app.get('/', function (req, res) {
res.sendfile("index.html");
});
app.get('/players', function (req, res) {
res.send(players);
});
io.on('connection', function (socket) {
let userId;
socket.on('disconnect', function (reason) {
console.log(reason);
players = players.filter(function (obj) {
return obj.id !== userId;
});
console.log('player left '+userId);
io.emit('players', players);
});
socket.on('new player', function (id, name) {
userId = id;
players.push({
name: name
, id: id
, round: 0
, roll: null
});
io.emit('players', players);
});
io.emit('players', players);
});
app.js
Uuid create a User ID
npm install uuid
https://www.npmjs.com/package/uuid
Creates a unique id for every connection.
const port = 3000;
const http = require('http')
const express = require('express');
const app = express();
const server = http.createServer(app);
const uuidv1 = require('uuid/v1');
server.listen(port);
console.log('Listening on port ' + port);
app.get('/', function (req, res) {
console.log(uuidv1());
res.sendFile(__dirname + '/index.html');
});
app.get('/id', function (req, res) {
console.log(uuidv1());
res.json({
id: uuidv1()
});
});
Battle Game - Multiplayer - index.html
<h1 class="message"></h1>
<div class="output"></div>
<input name="user" type="text" value="Laurence">
<button class="btn1">Join</button>
<button class="btn2">Roll</button>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const output = document.querySelector('.output');
const message = document.querySelector('.message');
const btn1 = document.querySelector('.btn1');
const btn2 = document.querySelector('.btn2');
const user = document.querySelector('input[name=user]');
btn1.addEventListener('click', function () {
let id = 'player_' + Math.floor(Date.now() * Math.random());
socket.emit('new player', id, user.value);
user.style.display = 'none';
btn1.style.display = 'none';
})
btn2.addEventListener('click', function () {
socket.emit('roll');
btn2.disabled = true;
})
socket.on('players', listPlayers);
socket.on('inplay', checkWinner);
function checkWinner(data) {
message.innerHTML = data;
btn2.disabled = false;
}
function listPlayers(players) {
message.textContent = players.length > 0 ? `Round
${players[0].round} ` : `First Round 0`;
output.innerHTML = 'Players<br>';
players.forEach(function (player) {
let div = document.createElement('div');
div.textContent = `${player.name} roll = ${player.roll}`;
div.style.color = player.winner ? 'green' : 'black';
output.appendChild(div);
})
}
</script>
Battle Game - Multiplayer - app.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const http = require('http').Server(app);
const io = require('socket.io')(http);
const lodash = require('lodash');
let players = [];
let round = 0;
const bodyParser = require('body-parser');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(__dirname + '/public'));
http.listen(port, function () {
console.log("Ready " + port);
})
app.get('/', function (req, res) {
res.sendfile("index.html");
});
app.get('/players', function (req, res) {
res.send(players);
});
io.on('connection', function (socket) {
let userId;
socket.on('disconnect', function (reason) {
players = players.filter(function (obj) {
return obj.id !== userId;
});
nextRoundCheck();
});
socket.on('new player', function (id, name) {
userId = id;
players.push({
name: name
, id: id
, round: round
, roll: null
, winner: false
});
io.emit('players', players);
});
socket.on('roll', function () {
players.forEach(function (player) {
if (player.id == userId) {
player.roll = lodash.random(1, 1000);
}
})
nextRoundCheck();
});
io.emit('players', players);
});
Battle Game - Multiplayer - app.js
function nextRoundCheck() {
if (players.length > 0) {
let ready = 0;
let top = 0;
let win = 0;
players.forEach(function (player, index) {
player.winner = false;
if (player.roll) {
ready++;
if (player.roll && player.roll > top) {
win = index;
top = player.roll;
}
}
})
players[win].winner = true;
io.emit('players', players);
if (ready >= players.length) {
io.emit('inplay', 'Round #' + round + ' winner is ' + players[win].name);
round++;
players.forEach(function (player, index) {
player.winner = false;
player.roll = null;
player.round = round;
})
}
}
}
Congratulations on completing the section
This ebook uses https://developer.mozilla.org/en-US/docs/Web/JavaScript as a source for examples. Check out
more about JavaScript at MDN.
Find out more about my courses at http://www.discoveryvip.com/
Course instructor : Laurence Svekis -
providing online training to over
500,000 students across hundreds of
courses and many platforms.

More Related Content

What's hot

Apache installation and configurations
Apache installation and configurationsApache installation and configurations
Apache installation and configurationsNikhil Jain
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.jsConFoo
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js ExplainedJeff Kunkle
 
Networking and Go: An Engineer's Journey (Strangeloop 2019)
Networking and Go: An Engineer's Journey (Strangeloop 2019)Networking and Go: An Engineer's Journey (Strangeloop 2019)
Networking and Go: An Engineer's Journey (Strangeloop 2019)Sneha Inguva
 
Php through the eyes of a hoster phpbnl11
Php through the eyes of a hoster phpbnl11Php through the eyes of a hoster phpbnl11
Php through the eyes of a hoster phpbnl11Combell NV
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scriptingTony Fabeen
 
nginx: writing your first module
nginx: writing your first modulenginx: writing your first module
nginx: writing your first moduleredivy
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
Fluentd meetup dive into fluent plugin (outdated)
Fluentd meetup dive into fluent plugin (outdated)Fluentd meetup dive into fluent plugin (outdated)
Fluentd meetup dive into fluent plugin (outdated)N Masahiro
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Fluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshellFluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshellN Masahiro
 
PM : code faster
PM : code fasterPM : code faster
PM : code fasterPHPPRO
 
Final opensource record 2019
Final opensource record 2019Final opensource record 2019
Final opensource record 2019Karthik Sekhar
 
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
 

What's hot (20)

Apache installation and configurations
Apache installation and configurationsApache installation and configurations
Apache installation and configurations
 
The basics of fluentd
The basics of fluentdThe basics of fluentd
The basics of fluentd
 
Fluentd introduction at ipros
Fluentd introduction at iprosFluentd introduction at ipros
Fluentd introduction at ipros
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 
Networking and Go: An Engineer's Journey (Strangeloop 2019)
Networking and Go: An Engineer's Journey (Strangeloop 2019)Networking and Go: An Engineer's Journey (Strangeloop 2019)
Networking and Go: An Engineer's Journey (Strangeloop 2019)
 
Php through the eyes of a hoster phpbnl11
Php through the eyes of a hoster phpbnl11Php through the eyes of a hoster phpbnl11
Php through the eyes of a hoster phpbnl11
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scripting
 
nginx: writing your first module
nginx: writing your first modulenginx: writing your first module
nginx: writing your first module
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Fluentd meetup dive into fluent plugin (outdated)
Fluentd meetup dive into fluent plugin (outdated)Fluentd meetup dive into fluent plugin (outdated)
Fluentd meetup dive into fluent plugin (outdated)
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Fluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshellFluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshell
 
PM : code faster
PM : code fasterPM : code faster
PM : code faster
 
Final opensource record 2019
Final opensource record 2019Final opensource record 2019
Final opensource record 2019
 
NodeJS
NodeJSNodeJS
NodeJS
 
Node.js
Node.jsNode.js
Node.js
 
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.
 

Similar to Introduction to Node js for beginners + game project

Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLaurence Svekis ✔
 
Introduction to Node JS1.pdf
Introduction to Node JS1.pdfIntroduction to Node JS1.pdf
Introduction to Node JS1.pdfBareen Shaikh
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSCosmin Mereuta
 
Node.js in action
Node.js in actionNode.js in action
Node.js in actionSimon Su
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Lucas Jellema
 
Nodejs quick start
Nodejs quick startNodejs quick start
Nodejs quick startGuangyao Cao
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsSu Zin Kyaw
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
 
Ansible new paradigms for orchestration
Ansible new paradigms for orchestrationAnsible new paradigms for orchestration
Ansible new paradigms for orchestrationPaolo Tonin
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsAdrien Guéret
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.jsAyush Mishra
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 

Similar to Introduction to Node js for beginners + game project (20)

Node js
Node jsNode js
Node js
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
Introduction to Node JS1.pdf
Introduction to Node JS1.pdfIntroduction to Node JS1.pdf
Introduction to Node JS1.pdf
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
node js.pptx
node js.pptxnode js.pptx
node js.pptx
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 
Ferrara Linux Day 2011
Ferrara Linux Day 2011Ferrara Linux Day 2011
Ferrara Linux Day 2011
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node js beginner
Node js beginnerNode js beginner
Node js beginner
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)
 
Nodejs quick start
Nodejs quick startNodejs quick start
Nodejs quick start
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Nodejs
NodejsNodejs
Nodejs
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
Book
BookBook
Book
 
Ansible new paradigms for orchestration
Ansible new paradigms for orchestrationAnsible new paradigms for orchestration
Ansible new paradigms for orchestration
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 

More from Laurence Svekis ✔

Quiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScriptQuiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScriptLaurence Svekis ✔
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence Svekis ✔
 
10 java script projects full source code
10 java script projects full source code10 java script projects full source code
10 java script projects full source codeLaurence Svekis ✔
 
Chrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers GuideChrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers GuideLaurence Svekis ✔
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptLaurence Svekis ✔
 
Web development resources brackets
Web development resources bracketsWeb development resources brackets
Web development resources bracketsLaurence Svekis ✔
 
Google Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with CodeGoogle Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with CodeLaurence Svekis ✔
 
JavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive CodeJavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive CodeLaurence Svekis ✔
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeLaurence Svekis ✔
 
Monster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applicationsMonster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applicationsLaurence Svekis ✔
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptLaurence Svekis ✔
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereLaurence Svekis ✔
 

More from Laurence Svekis ✔ (20)

Quiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScriptQuiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScript
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
 
Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
Code examples javascript ebook
Code examples javascript ebookCode examples javascript ebook
Code examples javascript ebook
 
Javascript projects Course
Javascript projects CourseJavascript projects Course
Javascript projects Course
 
10 java script projects full source code
10 java script projects full source code10 java script projects full source code
10 java script projects full source code
 
Chrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers GuideChrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers Guide
 
Brackets code editor guide
Brackets code editor guideBrackets code editor guide
Brackets code editor guide
 
Web hosting get start online
Web hosting get start onlineWeb hosting get start online
Web hosting get start online
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
Web hosting Free Hosting
Web hosting Free HostingWeb hosting Free Hosting
Web hosting Free Hosting
 
Web development resources brackets
Web development resources bracketsWeb development resources brackets
Web development resources brackets
 
Google Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with CodeGoogle Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with Code
 
JavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive CodeJavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive Code
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
 
Monster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applicationsMonster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applications
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScript
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript Here
 

Recently uploaded

Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime NagercoilNagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoilmeghakumariji156
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdfMatthew Sinclair
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查ydyuyu
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查ydyuyu
 
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsRussian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsMonica Sydney
 
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac RoomVip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Roommeghakumariji156
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查ydyuyu
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirtrahman018755
 
Power point inglese - educazione civica di Nuria Iuzzolino
Power point inglese - educazione civica di Nuria IuzzolinoPower point inglese - educazione civica di Nuria Iuzzolino
Power point inglese - educazione civica di Nuria Iuzzolinonuriaiuzzolino1
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrHenryBriggs2
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...gajnagarg
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"growthgrids
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdfMatthew Sinclair
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...kajalverma014
 
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdfMatthew Sinclair
 
75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptx75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptxAsmae Rabhi
 
Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.krishnachandrapal52
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasDigicorns Technologies
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样ayvbos
 

Recently uploaded (20)

Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime NagercoilNagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
 
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsRussian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
 
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac RoomVip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
Power point inglese - educazione civica di Nuria Iuzzolino
Power point inglese - educazione civica di Nuria IuzzolinoPower point inglese - educazione civica di Nuria Iuzzolino
Power point inglese - educazione civica di Nuria Iuzzolino
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
 
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
 
75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptx75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptx
 
Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency Dallas
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
 

Introduction to Node js for beginners + game project

  • 2. Node Course Guide This guide is designed to supplement the Introduction to Node js for beginners + game project Course It includes source code that follows the lessons of the course. One of the best ways to learn is to try the code out for yourself. Thanks for taking the course, if you have any questions or need clarification on the content please let me know in the Q&A section. Happy Coding …..
  • 3. What is Node and how does it work JavaScript on the server. ● run JavaScript on the server ● open source server environment ● can connect to a database ● Create, open, read write, delete files on your server ● Generate page content Node.js runs single-threaded, asynchronously programming, which is very memory efficient.
  • 4. Server-side JavaScript JavaScript uses browsers to run code on the frontend. On the backend needs to be interpreted (executed). Node.js uses Google’s V8 VM which is the same runtime environment the Chrome uses. Node.js comes with many useful modules - saves from writing from scratch. Node is runtime environment and a library
  • 5. Node.js - Install Node files have a js extension Download and install node at https://nodejs.org Terminal - for command line interface Node package manager - share code and reuse existing code. Faster development. https://www.npmjs.com/ Install https://www.npmjs.com/get-npm You will also need an editor - brackets.io
  • 6. Windows Terminal Windows - https://cmder.net/ or use the command prompt terminal Launch the Command Prompt - use the Run window or press the Win + R keys on your keyboard. Then, type cmd and press Enter. List current directory of files - dir Change directory to D drive - cd D: Change directory down one level - cd.. Change directory to folder by name - cd folder Make new folder - mkdir folderName Get help - help
  • 7. Mac Terminal Open Terminal by pressing Command+Space or select terminal in the applications list. List current directory of files - ls Change directory to D drive - cd D: Change directory down one level - cd.. Change directory to folder by name - cd folder Make new folder - mkdir folderName Get help - help
  • 8. Command Line Launch One node is installed check to see version installed. Type node -v Open your editor and create a js file that contains console.log('Hello World'); save it as test.js In the terminal type node test.js and watch for a result. What gets returned? NPM - check if its installed npm -v latest version install npm install npm@latest -g
  • 9. First Node File One node is installed check to see version installed. Type node -v Open your editor and create a js file that contains console.log('Hello World'); save it as test.js In the terminal type node test.js and watch for a result. What gets returned?
  • 10. Node file in the browser To run the file in a browser you need to serve the web pages. HTTP server URL where the content will render. Map requests and show pages. Request handlers on the server side to show page. Viewing logic to send content to users browser. NODE can do all this…
  • 11. First Node HTTP File Require directive - loads the http module and stores the returned HTTP instance as a variable. Create Server method. http.createServer() Bind it to port 8080 .listen(8080) Write to the response writeHead method. Set status code to 200 success okay and specify content type. text/plain Add body with content end method. Save the file as app.js open the terminal type node app.js then open your browser to http://localhost:8080/ var http = require('http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World!'); }).listen(8080);
  • 12. Try the Code var http = require("http"); http.createServer(function (request, response) { response.writeHead(200, { "Content-Type": "text/plain" }); response.write("Hello World"); response.end(); }).listen(8080);
  • 13. Node How it works Node uses a single process - where as other languages like PHP would open a new process for every HTTP request. Callback is an asynchronous equivalent for a function. (event-driven, asynchronous callbacks allow for moving to the next line.) function message(greeting, callback) { console.log(`${greeting}.`); callback(); // afterwards gets invoked here } function afterwards(){ console.log('GoodBye!'); } message('Hello', afterwards);
  • 14. Node modules Modules in node are like JavaScript libraries. Pre Written code that you can pull into your project and use. Node.js has a set of built-in modules which you can use without any additional installation. To include a module, use the require() function with the name of the module. var http = require('http');
  • 15. Module A module is a JavaScript library/file that you can import into other code using Node's require() function https://www.npmjs.com/ https://www.npmjs.com/search?q=tw itter
  • 16. Create a module Allows you to easily reuse code. //file called module.js exports.greeting = "hello world"; //file called testmod.js const output = require('./module.js') console.log(output.greeting);
  • 17. Node web server const http = require("http"); //loads module called http function req(request, response) { //callback function response.writeHead(200, { //sends HTTP status 200 "Content-Type": "text/plain" }); response.write("Hello World"); //page content response body response.end(); //finish the response. } http.createServer(req).listen(8080); //method creates an HTTP server console.log('Server started');
  • 18. Files on your server Read index1.html to your web browser. const http = require('http'); const fs = require('fs'); function req(request, response) { fs.readFile('index1.html', function (error, data) { response.writeHead(200, { 'Content-Type': 'text/html' }); response.write(data); response.end(); }) } http.createServer(req).listen(8080); console.log('Server started'); <html> <head> <title>JavaScript</title> </head> <body> <h1>Welcome</h1> <p>I enjoy JavaScript.</p> </body> </html>
  • 19. Node URL pathname request const http = require('http'); const url = require('url'); function onRequest(request, response) { const base = url.parse(request.url); const pathname = base.pathname; console.log(pathname + ' received.'); response.writeHead(200, { 'Content-Type': 'text/plain' }); response.write('Welcome'); response.end(); } http.createServer(onRequest).listen(8080); console.log('Started'); http://localhost:8080/foo Default is to look for favicon on every page.
  • 20. Node Routing const http = require('http'); const url = require('url'); const fs = require('fs'); function onRequest(request, response) { const base = url.parse(request.url); const fileName = '.' + base.pathname; fs.readFile(fileName, function (error, data) { if (error) { response.writeHead(404, { 'Content-Type': 'text/html' }); return response.end('<h1>Not Found</h1>'); } response.writeHead(200, { 'Content-Type': 'text/html' }); response.write(data); return response.end(); }) } http.createServer(onRequest).listen(8080); console.log('Started'); Create some pages on your directory. Load them in your browser.
  • 21. File Write and Read const fs = require('fs'); fs.readFile('./db.json', 'utf-8', function (err, data) { const d = JSON.parse(data); //data from db.json console.log(d.message); }) fs.readdir('./', function (err, data) { console.log(data); // all directories from folder }) const temp = { greeting: 'Welcome to Node' //js object } fs.writeFile('db1.json', JSON.stringify(temp), function (error) { //stringify to JSON console.log('file created'); }) Node makes it easy to write and read files from your computer. You can also read directories. readFile use utf-8 as the character code readdir - to read the directory file names writeFile - to write to or create a file. {"message":"Hello World"}
  • 22. Loading Packages NPM Popular package called lodash https://www.npmjs.com/package/lodash npm install lodash ● Installs a new folder with all dependant files. ● Warnings if no package.json which lists dependant packages package.json - Specifics of npm's package.json handling. At the heart of node system all metadata for the project making it easier to package and redistribute. You can create a package.json file npm init Answer the questions to complete Short format is npm init --yes
  • 23. Lodash Quick https://lodash.com/ - https://lodash.com/docs/4.17.11 First setup Lodash if you haven’t already. npm init - to create package.json file in folder npm install lodash - to install package -g to install current package as a global package (npm i -g npm) shorthand i is for install then last parameter is the package name. npm install - will install all modules listed as dependencies in package.json . const _ = require('lodash'); let randomNum1 = _.random(10); // 0-10 random number let randomNum2 = _.random(1, 100); // 0-10 random number console.log(randomNum1); console.log(randomNum2); let myArr = ['apple', 'orange', 'banana', 'blue berry', 'grape', 'cherry']; let randomItem = _.sample(myArr); console.log(randomItem); console.log(myArr); console.log(_.shuffle(myArr)); console.log(_.shuffle(myArr)); let counter = 0; _.times(5, function () { //Loops 5 times counter++; console.log(counter); }) let arr2 = _.map(myArr, function (item) { console.log(item); return item.toUpperCase(); }) console.log(arr2); console.log(_.map(myArr, _.camelCase)); console.log(_.map(myArr, _.capitalize)); console.log(_.map(myArr, _.upperCase)); console.log(_.map(myArr, _.lowerCase)); //return items that start with let arr3 = _.map(myArr, function (e) { return _.startsWith(e, 'b'); }) console.log(arr3); let arr4 = _.map(myArr, function (e) { return _.endsWith(e, 'e'); }) console.log(arr4); myArr.forEach(function (e) { if (_.endsWith(e, 'e')) { console.log(e); } });
  • 24. Packages Express Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. https://expressjs.com/ npm install express --save http://localhost:3000/ const express = require('express'); const app = express(); const port = 3000; app.get('/', function (req, res) { res.send('Hello World!'); }); app.get('/about', function(req, res) { res.send('About Page'); }); app.listen(port, function () { return console.log("Port is ".concat(port, "!")); });
  • 25. Express static files __dirname is the directory that will be used. http://localhost:3000/index1.html http://localhost:3000 const express = require('express'); const app = express(); const port = 3000; app.use(express.static(__dirname)); // change directory to root app.listen(port, function () { return console.log("Port is "+port + ' '+ __dirname); }); http://localhost:3000/2 http://localhost:3000 const express = require('express'); const app = express(); const port = 3000; app.get('/', function (req, res) { res.sendFile(__dirname +'/index1.html'); }); app.get('/2', function (req, res) { res.sendFile(__dirname +'/index2.html'); }); app.listen(port, function () { return console.log("Port is "+port + ' '+ __dirname); });
  • 26. NodeMon Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development. npm install -g nodemon https://nodemon.io/ Run it nodemon app.js ** make some changes no more node restart typing ;)
  • 27. Get data <button>Click</button> <div class="output"></div> <script> const btn = document.querySelector('button'); const output = document.querySelector('.output'); btn.addEventListener('click', listUsers); function listUsers() { fetch('users').then(function (response) { return response.json(); }).then(function (data) { output.innerHTML = "Users<br>"; data.forEach(function (el) { let div = document.createElement('div'); div.textContent = el.user + ' ' + el.pass; output.appendChild(div); }) }); } </script> const express = require('express'); const app = express(); app.use(express.static(__dirname)); const users = [{ user: 'Laurence', pass: 'secret' }, { user: 'Jane', pass: 'password' }]; app.get('/users', function (req, res) { res.send(users); }); const server = app.listen(3000, function () { console.log('server' + server.address().port); });
  • 28. Body-parser Parse incoming request bodies in a middleware before your handlers npm install body-parser https://www.npmjs.com/package/body-parser Send data from the front end code form to the backend. <form id="myform" action="login" method="post"> <input type="text" name="user" value="User Name"> <input type="text" name="pass" value="Password"> </form> <div class="btn">Click Me</div> <script> const btn = document.querySelector('.btn'); btn.addEventListener('click', function () { const formData = new FormData(document.forms[0]); const searchParams = new URLSearchParams(); for (const val of formData) { console.log(val); searchParams.append(val[0], val[1]); } fetch('/login', { method: 'post' , body: searchParams }).then(function (response) { return response.json() }).then(function (data) { return console.log(data); }) }) </script>
  • 29. Body-parser Middleware to get data const express = require('express'); const app = express(); const port = 3000; const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // for parsing application/json app.use(express.static(__dirname + '/public')); app.get('/', function (req, res) { res.sendfile("index.html"); }); app.post('/login', function (req, res) { let userName = req.body.user; let password = req.body.pass; console.log("UserName = " + userName + ", password = " + password); res.json({ status: true }); }); app.listen(3000, function () { console.log("PORT " + port); })
  • 30. Socket.io https://socket.io/ const express = require('express'); const app = express(); const port = 3000; const http = require('http').Server(app); const socket = require('socket.io')(http); app.use(express.static(__dirname + '/public')); app.get('/', function (req, res) { res.sendfile("index.html"); }); socket.on('connection', function (s) { console.log('user ready'); }) const server = http.listen(port, function () { console.log("Ready " + port); }) <input name="user" type="text" value="Laurence"> <button class="btn">Roll</button> <script src="/socket.io/socket.io.js"></script> <script> const socket = io(); //initialization of socket connection const btn = document.querySelector('.btn'); btn.addEventListener('click', function () { }) </script>
  • 31. Socket.io send message to users https://socket.io/docs/emit-cheatsheet/ http://localhost:3000/players - list players http://localhost:3000/ - join game <div class="output"></div><input name="user" type="text" value="Laurence"><button class="btn1">Join</button> <script src="/socket.io/socket.io.js"></script> <script> const socket = io(); const output = document.querySelector('.output'); const btn1 = document.querySelector('.btn1'); const user = document.querySelector('input[name=user]'); btn1.addEventListener('click', function () { var id = 'player_' + Math.floor(Date.now() * Math.random()); socket.emit('new player', id, user.value); user.style.display = 'none'; btn1.style.display = 'none'; }) socket.on('players', listPlayers); function listPlayers(players) { output.innerHTML = 'Players<br>'; players.forEach(function (player) { let div = document.createElement('div'); div.textContent = player.name; output.appendChild(div); }) } </script> index.html
  • 32. const express = require('express'); const app = express(); const port = process.env.PORT || 3000; const http = require('http').Server(app); const io = require('socket.io')(http); let players = []; const bodyParser = require('body-parser'); app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(__dirname + '/public')); http.listen(port, function () { console.log("Ready " + port); }) app.get('/', function (req, res) { res.sendfile("index.html"); }); app.get('/players', function (req, res) { res.send(players); }); io.on('connection', function (socket) { let userId; socket.on('disconnect', function (reason) { console.log(reason); players = players.filter(function (obj) { return obj.id !== userId; }); console.log('player left '+userId); io.emit('players', players); }); socket.on('new player', function (id, name) { userId = id; players.push({ name: name , id: id , round: 0 , roll: null }); io.emit('players', players); }); io.emit('players', players); }); app.js
  • 33. Uuid create a User ID npm install uuid https://www.npmjs.com/package/uuid Creates a unique id for every connection. const port = 3000; const http = require('http') const express = require('express'); const app = express(); const server = http.createServer(app); const uuidv1 = require('uuid/v1'); server.listen(port); console.log('Listening on port ' + port); app.get('/', function (req, res) { console.log(uuidv1()); res.sendFile(__dirname + '/index.html'); }); app.get('/id', function (req, res) { console.log(uuidv1()); res.json({ id: uuidv1() }); });
  • 34. Battle Game - Multiplayer - index.html <h1 class="message"></h1> <div class="output"></div> <input name="user" type="text" value="Laurence"> <button class="btn1">Join</button> <button class="btn2">Roll</button> <script src="/socket.io/socket.io.js"></script> <script> const socket = io(); const output = document.querySelector('.output'); const message = document.querySelector('.message'); const btn1 = document.querySelector('.btn1'); const btn2 = document.querySelector('.btn2'); const user = document.querySelector('input[name=user]'); btn1.addEventListener('click', function () { let id = 'player_' + Math.floor(Date.now() * Math.random()); socket.emit('new player', id, user.value); user.style.display = 'none'; btn1.style.display = 'none'; }) btn2.addEventListener('click', function () { socket.emit('roll'); btn2.disabled = true; }) socket.on('players', listPlayers); socket.on('inplay', checkWinner); function checkWinner(data) { message.innerHTML = data; btn2.disabled = false; } function listPlayers(players) { message.textContent = players.length > 0 ? `Round ${players[0].round} ` : `First Round 0`; output.innerHTML = 'Players<br>'; players.forEach(function (player) { let div = document.createElement('div'); div.textContent = `${player.name} roll = ${player.roll}`; div.style.color = player.winner ? 'green' : 'black'; output.appendChild(div); }) } </script>
  • 35. Battle Game - Multiplayer - app.js const express = require('express'); const app = express(); const port = process.env.PORT || 3000; const http = require('http').Server(app); const io = require('socket.io')(http); const lodash = require('lodash'); let players = []; let round = 0; const bodyParser = require('body-parser'); app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(__dirname + '/public')); http.listen(port, function () { console.log("Ready " + port); }) app.get('/', function (req, res) { res.sendfile("index.html"); }); app.get('/players', function (req, res) { res.send(players); }); io.on('connection', function (socket) { let userId; socket.on('disconnect', function (reason) { players = players.filter(function (obj) { return obj.id !== userId; }); nextRoundCheck(); }); socket.on('new player', function (id, name) { userId = id; players.push({ name: name , id: id , round: round , roll: null , winner: false }); io.emit('players', players); }); socket.on('roll', function () { players.forEach(function (player) { if (player.id == userId) { player.roll = lodash.random(1, 1000); } }) nextRoundCheck(); }); io.emit('players', players); });
  • 36. Battle Game - Multiplayer - app.js function nextRoundCheck() { if (players.length > 0) { let ready = 0; let top = 0; let win = 0; players.forEach(function (player, index) { player.winner = false; if (player.roll) { ready++; if (player.roll && player.roll > top) { win = index; top = player.roll; } } }) players[win].winner = true; io.emit('players', players); if (ready >= players.length) { io.emit('inplay', 'Round #' + round + ' winner is ' + players[win].name); round++; players.forEach(function (player, index) { player.winner = false; player.roll = null; player.round = round; }) } } }
  • 37. Congratulations on completing the section This ebook uses https://developer.mozilla.org/en-US/docs/Web/JavaScript as a source for examples. Check out more about JavaScript at MDN. Find out more about my courses at http://www.discoveryvip.com/ Course instructor : Laurence Svekis - providing online training to over 500,000 students across hundreds of courses and many platforms.