sources reskilling program...• node.js uses asynchronous programming! 4 interne orange used by...
TRANSCRIPT
SourcesReskilling Program
2 Interne Orange
• Node.js is an open source server environment.
• Node.js allows you to run JavaScript on the server.
• Node.js is written in C++
• Node.js® is a JavaScript runtime built onChrome's V8 JavaScript engine.
• Node.js is free
• Node.js runs on various platforms(Windows, Linux, Unix, Mac OS X, etc.)
3 Interne Orange
Why node ? • Fast, efficient and highly scalabale
• Event driven, non blocking I/O model
• Popular in industry
• Same language on the front and the back end
• The MEAN stack ( Mongo Express Angular NodeJS)
• Node.js uses asynchronous programming!
4 Interne Orange
Used by many modern companies :
• Linkedin• Wal-Mart• Paypal• Uber• Netflix
5 Interne Orange
6 Interne Orange
Menu
0) Js reviews ?1) NodeJS2) Npm3) Express4) Socket IO
7 Interne Orange
If you have more blocking operations, the event queue gets even worse:
If you have more blocking operations, the vent queue gets even worse:
https://www.youtube.com/watch?time_continue=2&v=8aGhZQkoFbQ
8 Interne Orange
The Event Loop is a queue of callback functions. When an async function executes, the callbackfunction is pushed into the queue. The JavaScript engine doesn't start continue processingthe event loop until the code after an async function has executed.
9 Interne Orange
Reference
https://www.w3schools.com/nodejs/default.asp
http://debuggable.com/posts/understanding-node-js:4bd98440-45e4-4a9a-8ef7-0f7ecbdd56cb
https://openclassrooms.com/fr/courses/1056721-des-applications-ultra-rapides-avec-node-js/1057364-les-modules-node-js-et-npm
https://thinkmobiles.com/blog/node-js-app-examples/
https://www.tutorialsteacher.com/nodejs/nodejs-tutorials
Videos :
https://www.youtube.com/watch?v=RLtyhwFtXQA&feature=youtu.be
https://www.youtube.com/watch?v=pU9Q6oiQNd0&feature=youtu.be
https://www.youtube.com/watch?v=fBNz5xF-Kx4
10 Interne Orange
Prerquities
https://www.toptal.com/nodejs/why-the-hell-would-i-use-node-js
• Know client / server protocol
• Confortable with JS / ES6
• Have already use a framework
11 Interne Orange
Download Node.js from the official Node.js web site:
https://nodejs.org
12 Interne Orange
13 Interne Orange
Test Node --version
14 Interne Orange
Hello world n°1
Create a folderCreate a file and write :
console.log('hello world !');
Then execute using node <your filename>
15 Interne Orange
Hello world n°2
var http = require('http');
http.createServer( function (req, res) {res.writeHead(200, {'Content-Type': 'text/plain'});res.end('Hello World!');
}).listen(8084);
16 Interne Orange
ReminderTo stop an application :
17 Interne Orange
Hello world n°2Sending html
var http = require('http');
var server = http.createServer( function (req, res) {res.writeHead(200, {"Content-Type": "text/html"});res.end('<p>Voici un paragraphe <strong>HTML
</strong> !</p>');});server.listen(8084);
18 Interne Orange
Hello world n°2Acces variable env
var http = require('http');
const PORT = process.env.NODEPORT || 8084 ;
// this is a comment var server = http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});res.end('<p>Voici un paragraphe <strong>HTML</strong> !</p>');
});server.listen(PORT,() =>console.log(` Server running on port ${PORT}`));
19 Interne Orange
Hello world n°2FS
(file system)
• fs.access(): check if the file exists and Node.js can access it with its permissions• fs.appendFile(): append data to a file. If the file does not exist, it's created• fs.chmod(): change the permissions of a file specified by the filename passed.
Related: fs.lchmod(), fs.fchmod()• fs.chown(): change the owner and group of a file specified by the filename passed.
Related: fs.fchown(), fs.lchown()• fs.close(): close a file descriptor• fs.copyFile(): copies a file• fs.createReadStream(): create a readable file stream• fs.createWriteStream(): create a writable file stream• fs.link(): create a new hard link to a file• fs.mkdir(): create a new folder• fs.mkdtemp(): create a temporary directory
The fs module provides a lot of very useful functionality to access and interact with the file system.
20 Interne Orange
Hello world n°2FS
(file system)
• fs.open(): set the file mode• fs.readdir(): read the contents of a directory• fs.readFile(): read the content of a file. Related: fs.read()• fs.readlink(): read the value of a symbolic link• fs.realpath(): resolve relative file path pointers (., ..) to the full path• fs.rename(): rename a file or folder• fs.rmdir(): remove a folder• fs.stat(): returns the status of the file identified by the filename passed. Related:
fs.fstat(), fs.lstat()• fs.symlink(): create a new symbolic link to a file• fs.truncate(): truncate to the specified length the file identified by the filename
passed. Related: fs.ftruncate()• fs.unlink(): remove a file or a symbolic link• fs.unwatchFile(): stop watching for changes on a file• fs.utimes(): change the timestamp of the file identified by the filename passed.
Related: fs.futimes()• fs.watchFile(): start watching for changes on a file. Related: fs.watch()• fs.writeFile(): write data to a file. Related: fs.write()
21 Interne Orange
Hello world n°2FS
(file system)
const path = require('path');const fs = require('fs');
// base file name console.log(path.basename( __filename ))
//directory name console.log(path.dirname( __filename ))
//file extentionconsole.log(path.extname( __filename ))
//create path object console.log(path.parse(__filename).base)
// create a directoryfs.mkdir(path.join(__dirname,'test'), {}, err => {
if (err) throw err;console.log('Folder created...');
});
22 Interne Orange
Hello world n°2FS
(file system)
var http = require('http');
var fs = require('fs');
http.createServer( function (req, res) {
fs.readFile('demofile1.html', function ( err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});res.write(data);res.end();
})
}).listen(8080); );
23 Interne Orange
24 Interne Orange
What is a Module in Node.js?
Consider modules to be the same as JavaScript libraries.A set of functions you want to include in your application.
25 Interne Orange
What do we have here?
var http = require('http');
http.createServer(function (req, res) {res.writeHead(200, {'Content-Type': 'text/plain'});res.end('Hello World!');
}).listen(8080);
Importinga module
Callback function
(trigged whenready)
26 Interne Orange
Include Your Own Module, Step 1 : make it
Create a module that returns the current date and time:
exports.myDateTime = function () {return Date();
};
Use the exports keyword to make properties and methods available outside the module file.
27 Interne Orange
Include Your Own Module Step 2 : use it
Use the module "myfirstmodule" in a Node.js file:var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {res.writeHead(200, {'Content-Type': 'text/html'});res.write("The date and time are currently: " + dt.myDateTime());res.end();
}).listen(8080);
28 Interne Orange
Using argument when running
If you have one argument without an index name, like this:
node app.js flavio you can access it using
const args = process.argv.slice(2) args[0] In this case:
node app.js name=flavio args[0] is name=flavio,
and you need to parse it.
29 Interne Orange
30 Interne Orange
As simple as
npm install upper-case
31 Interne Orange
Java - Apache maven
Php - composer
Python - pip
Linux - Apt get
Ruby - gem
Node Package Manager
32 Interne Orange
NPM
Install 3rd party package ( frameorks, libraires, tools, etc )
Packages get stored in the « node_modules » folder
All dependencies are listed in a « package.json » file
Npm scripts can be created to run certain tacks such as run a server
34 Interne Orange
35 Interne Orange
Set proxy
npm config set proxy http://mydomain\username:[email protected]:8181/proxy.pac
npm config set https-proxy http://mydomain\username:[email protected]:8181/proxy.pac
Reminder : http://username:[email protected]:8080
36 Interne Orange
Check config with npm get config proxy
Change proxy https value from https:// to http://
37 Interne Orange
38 Interne Orange
npm config set registry https://artifactory-iva.si.francetelecom.fr/artifactory/api/npm/npmproxy
npm config set registry https://artifactory-iva.si.francetelecom.fr/artifactory/api/npm/npmproxy
Using IVA repository
39 Interne Orange
package.json
package.json Equivalent to pom.xml, composer.json …
https://docs.npmjs.com/files/package.json
40 Interne Orange
package.json
package.json
there are lots of things going on here:
• name sets the application/package name• version indicates the current version• description is a brief description of the app/package• main set the entry point for the application• private if set to true prevents the app/package to be accidentally published on npm• scripts defines a set of node scripts you can run• dependencies sets a list of npm packages installed as dependencies• devDependencies sets a list of npm packages installed as development dependencies• engines sets which versions of Node this package/app works on• browserslist is used to tell which browsers (and their versions) you want to support
All those properties are used by either npm or other tools that we can use.
41 Interne Orange
package.json
package.json
The main property
In a Node.js application, it ‘s the entry point when the module is called via a require statement
main": "app.js",
The repository property
The repository property of a package.json is an array that defines where the source code for the module lives.
"repository": { "type": "git", "url": "https://github.com/bnb/metaverse.git"
}
42 Interne Orange
package.json
package.json
The dependencies property
where dependencies - the other modules that this module uses - are defined. The dependencies property takes an object that has the name and version at which each dependency should be used. Tying things back to the version property defined earlier, the version that a module needs is defined.
"dependencies": { "async": "^0.2.10", "npm2es": "~0.4.2", "optimist": "~0.6.0", "request": "~2.30.0", "skateboard": "^1.5.1", "split": "^0.3.0", "weld": "^0.2.2"
},
~: if you write ~0.13.0, you want to only update patch releases: 0.13.1 is ok,but 0.14.0 is not.
^: if you write ^0.13.0, you want to update patch and minor releases: 0.13.1, 0.14.0 and so on.*: if you write *, that means you accept all updates, including majorversion upgrades.>: you accept any version higher than the one you specify>=: you accept any version equal to or higher than the one you specify<=: you accept any version equal or lower to the one you specify<: you accept any version lower to the one you specifyX : is a wiild card
43 Interne Orange
package.json
package.json
The dependencies property
Till 0.4 excluded ( 0.3.999 ok ) :
"dependencies": { "markdown": "~0.3.5«
}
Till 1.0 excluded ( 0.99.99 ok ) :
"dependencies": { "markdown": "~0.3«
}
44 Interne Orange
package.json
NPM commands
npm install nameOfThePackage
npm uninstall nameOfThePackage
npm search whatIamLookingfor
npm update
npm ls (list local modules )
npm init // create package.json
npm audit // check non knows security failures
Npm – g // install globaly ( not for all project but cli)
45 Interne Orange
Generate an application from a
package.json
Generarate an application using express witha package.json file
npm install MONPACKAGE --save
or
npm install MONPACKAGE --save-dev
TP
46 Interne Orange
Testing an importedpackage
var http = require('http');var uc = require('upper-case');
http.createServer( function (req, res) {res.writeHead(200, {'Content-Type': 'text/html'});res.write(uc("Hello World!"));res.end();
}).listen( 8080 );
47 Interne Orange
Url
var http = require('http'); var url = require('url');
var server = http.createServer(function(req, res) { var page = url.parse(req.url).pathname; console.log(page); res.writeHead(200, {"Content-Type": "text/plain"}); res.write(‘Wellcome'); res.end();
}); server.listen(8080);
48 Interne Orange
var http = require('http');var url = require('url');
var server = http.createServer( function(req, res) {var page = url.parse(req.url).pathname;console.log(page);res.writeHead(200, {"Content-Type": "text/plain"});if (page == '/') {
res.write('Wellcome');}else if (page == '/contact') {
res.write(' send me an mail at [email protected]');}
res.end();});server.listen(8084);
49 Interne Orange
// serve static files var fs = require('fs'),
http = require('http');
http.createServer( function (req, res) {fs.readFile(__dirname + req.url, function (err,data) {
if (err) {res.writeHead(404);res.end(JSON.stringify (err));return;
}res.writeHead(200);res.end(data);
});}).listen(8080);
// this code does not correctly handle mime types.
50 Interne Orange
var static = require('node-static'); // don’t forget to install it ;)
//// Create a node-static server instance to serve the './public' folder//var file = new static.Server('./public');
require('http').createServer(function (request, response) {request.addListener('end', function () {
//// Serve files!//file.serve(request, response);
}).resume();}).listen(8080);
https://github.com/cloudhead/node-static
51 Interne Orange
Parameters
var http = require('http'); var url = require('url'); var querystring = require('querystring');
var server = http.createServer(function(req, res) { var params = querystring.parse(url.parse(req.url).query); res.writeHead(200, {"Content-Type": "text/plain"}); if (‘name' in params && ‘lastName' in params) {
res.write(‘your names is ' + params[‘name'] + ' ' + params[‘lastName']);
} else {
res.write(‘Please enter your names :'); } res.end();
}); server.listen(8080);
52 Interne Orange
Create a Login Formusing nodeJS
Test each step ! You have to find to be shure all is pertectly tested
Use an html template :https://colorlib.com/wp/html5-and-css3-login-forms/https://colorlib.com/wp/cat/login-forms/https://www.w3schools.com/howto/howto_css_login_form.asp
And create a small login page
If login/pass is wrong :Stay on the login page
Elsemove to a welcome page
TP
53 Interne Orange
Create a gallery
Create a gallery of images from a directory using FS
TP
const testFolder = './tests/'; const fs = require('fs'); fs.readdir ( testFolder, (err, files) => {
files.forEach( file => { console.log(file); });} );
// may be easier doing to 2 servers ?
54 Interne Orange
Create a gallery
Syncronise problem ???
TP const testFolder = './tests/';const fs = require('fs');const http = require('http');
const server = http.createServer( function (req, res) {
let filesImg = ''fs.readdir(testFolder).forEach(file => {
console.log(file);filesImg += ' <img src="'+ file +'" />'
});res.writeHead( 200 , {"Content-Type": "text/html"});res.end( '<p> kities !</p>' + filesImg );
});server.listen( 8084 );
=> readdirSync
55 Interne Orange
Send Event
var http = require('http'); var server = http.createServer(function(req, res) {
res.writeHead(200); res.end(‘Hi everyone!');
}); server.on('close', function() { // Listening for the close event
console.log('Bye bye !'); }) server.listen(8080); // Starting the serverserver.close(); // Stoping the server, trigg the event
Node.js is perfect for event-driven applications.
56 Interne Orange
var EventEmitter = require('events').EventEmitter;
var game = new EventEmitter();
game.on ('gameover', function(message){
console.log(message);});
game.emit ('gameover', ‘You loose !');
To go futher : http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
57 Interne Orange
game.emit ('gameover', ‘You loose !‘, ‘Patrick‘, 35,);
Event Name
Parameter1(Message )
Parameter3(score)
Parameter2( player )
Send as many parameters you like
58 Interne Orange
Call back VS event
var server = http.createServer(function(req, res) { });
var server = http.createServer(); server.on('request', function(req, res) { });=
59 Interne Orange
Node.js keeps a single thread for your code...
It really is a single thread running: you can't do any parallel code execution;
60 Interne Orange
...however, everything runs in parallel except your code
61 Interne Orange
62 Interne Orange
https://www.tutorialspoint.com/expressjs/index.htm
63 Interne Orange
=> npm install express
var express = require('express'); var app = express();
app.get('/', function(req, res) { res.setHeader('Content-Type', 'text/plain'); res.send('welcome to express Js');
});
app.listen(8080);
64 Interne Orange
Express routing
65 Interne Orange
Express routing
app.METHOD(PATH, HANDLER)
Where:• app is an instance of express.• METHOD is an HTTP request method, in lowercase.• PATH is a path on the server.• HANDLER is the function executed when the route is matched.
66 Interne Orange
Express routingRespond with Hello World! on the homepage:app.get('/', function (req, res) {
res.send('Hello World!') })
Respond to POST request on the root route (/), the application’s home page:app.post('/', function (req, res) {
res.send('Got a POST request') })
Respond to a PUT request to the /user route:app.put('/user', function (req, res) {
res.send('Got a PUT request at /user') })
Respond to a DELETE request to the /user route:app.delete('/user', function (req, res) {
res.send('Got a DELETE request at /user') })
67 Interne Orange
Express routingapp.route()
You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: Router() documentation.,Here is an example of chained route handlers that are defined by using app.route().app.route('/book')
.get( function (req, res) { res.send('Get a random book')
}) .post ( function (req, res) {
res.send('Add a book') }) .put( function (req, res) {
res.send('Update the book') })
68 Interne Orange
Route path
Routes are tested one after the other until one matches.
app.get('/path', function (req, res) {res.send('Hello World!');
});
'/ab?cd' // will match acd and abcd'/ab+cd' // will match abcd, abbcd, abbbcd, and soon'/ab*cd' // will match abcd, abxcd, abRABDOMcd, ab123cd, and so on'/ab(cd)?e' // will match /abe and /abcde/a/ // will match anything with an a in the route name/.*fly$/ // will match butterfly, dragonfly; but not butterflyman, dragonfly man, and so on
69 Interne Orange
Express routing – use files for routing
var express = require('express') var router = express.Router()
// middleware that is specific to this router router.use( function timeLog (req, res, next) {
console.log('Time: ', Date.now()) next()
})
// define the home page route router.get('/', function (req, res) {
res.send('Birds home page') })
// define the about route router.get('/about', function (req, res) {
res.send('About birds') })
module.exports = router
var express = require('express'); var app = express(); var birds = require('./birds')
app.use('/birds', birds )
// …..app.get('/', function(req, res) { res.setHeader('Content-Type', 'text/plain'); res.send('welcome to express Js'); });
app.listen(8080);
birds.js main.js
70 Interne Orange
Using ejs … npm install ejs …
app.get('/', function(req, res) { res.render('home.ejs' );
});
1) Genrate a folder views
2) Genrate a file home.ejs
3) Call your ejs
https://ejs.co/
71 Interne Orange
Ejs parameters
….app.get('/', function(req, res) {
let names = ['robert', 'Eltone', 'James', 'Mickeal'] ;res.render('home.ejs' , { namesToRender : names , a : ‘toto’ , b : 42} );
}); ….
<ul><% for (let name of namesToRender ) { %>
<li><%= name%></li> <% } %></ul>
App.js:
home.ejs:
72 Interne Orange
Ejs
Tags
•<% 'Scriptlet' tag, for control-flow, no output
•<%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
•<%= Outputs the value into the template (HTML escaped)
•<%- Outputs the unescaped value into the template
•<%# Comment tag, no execution, no output
•<%% Outputs a literal '<%'
•%> Plain ending tag
•-%> Trim-mode ('newline slurp') tag, trims following newline
•_%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it
73 Interne Orange
Ejs parameters
<% if (user) { %> <h2><%= user.name %></h2>
<% } %>
Includes<ul>
<% users.forEach(function(user){ %> <%- include('user/show', {user: user}); %> <% }); %>
</ul>
LayoutsEJS does not specifically support blocks, but layouts can be
implemented by including headers and footers, like so:
<%- include('header'); -%> <h1> Title </h1> <p> My page </p> <%- include('footer'); -%>
74 Interne Orange
Template engines for express
Pug: Haml-inspired template engine (formerly Jade).
Haml.js: Haml implementation.
EJS: Embedded JavaScript template engine.
hbs: Adapter for Handlebars.js, an extension of Mustache.js template
engine.
Squirrelly: Blazing-fast template engine that supports partials, helpers,
custom tags, and caching. Not white-space sensitive, works with any
language.
React: Renders React components on the server. It renders static markup
and does not support mounting those views on the client.
h4e: Adapter for Hogan.js, with support for partials and layouts.
hulk-hogan: Adapter for Twitter’s Hogan.js (Mustache syntax), with support
for Partials.
combyne.js: A template engine that hopefully works the way you’d expect.
swig: Fast, Django-like template engine.
Nunjucks: Inspired by jinja/twig.
marko: A fast and lightweight HTML-based templating engine that compiles
templates to CommonJS modules and supports streaming, async rendering
and custom tags. (Renders directly to the HTTP response stream).
whiskers: Small, fast, mustachioed.Blade: HTML Template Compiler, inspired by Jade & Haml.Haml-Coffee: Haml templates where you can write inline CoffeeScript.Webfiller: Plain-html5 dual-side rendering, self-configuring routes, organized source tree, 100% js.express-hbs: Handlebars with layouts, partials and blocks for express 3 from Barc.express-handlebars: A Handlebars view engine for Express whichdoesn’t suck.express-views-dom: A DOM view engine for Express.rivets-server: Render Rivets.js templates on the server.Exbars: A flexible Handlebars view engine for Express.Liquidjs: A Liquid engine implementation for both Node.js and browsers.express-tl: A template-literal engine implementation for Express.vuexpress: A Vue.js server side rendering engine for Express.js.Twing: First-class Twig engine for Node.js.
/* to change engine : */ app.set( 'view engine', 'jade' );
75 Interne Orange
Middlewares
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers.
Express est un framework basé sur le concept de middlewares.Ce sont des petits morceaux d'application qui rendent chacun un service spécifique. Vous pouvez charger uniquement les middlewares dont vous avez besoin
76 Interne Orange
77 Interne Orange
78 Interne Orange
Types of express middleware
•Application level middleware app.use
•Router level middleware router.use
•Built-in middleware express.static,express.json,express.urlencoded
•Error handling middleware app.use(err,req,res,next)
•Thirdparty middleware bodyparser,cookieparser
79 Interne Orange
var app = express();
app.use( function () {}) //added to all paths or globally
app.get('/someroute', function() {}) //added to a specific path
Middleware Usage:
To set up a middleware, you can invoke app.use() for every middleware layer that you want to add.
80 Interne Orange
Express – return code
app.use( function (err, req, res, next) { console.error(err.stack);
res.status(500).send('Something broke!');
// we are chaining instruction here, same as // res.status(500) ; res.send('Something broke!');
});
81 Interne Orange
SERVING STATIC FILES
express.static is the only built-in middleware in Expressvar options = {
dotfiles: 'ignore',etag: false,extensions: ['htm', 'html'],index: false,maxAge: '1d',redirect: false,setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());}
}app.use( express.static('public', options) );app.use( express.static('uploads') );app.use( express.static('files') );
82 Interne Orange
Create a TODO List
https://www.w3schools.com/howto/howto_js_todolist.asp
TP
83 Interne Orange
Create a TODO List
Test each step ! You have to find to be shure all is pertectly tested
First of all, we will consider the todo-list as a simple string array.
1) Create a simple hello world2) Create an express application 3) Create a route for a get on the home route4) Create a hello-world - html file and render it with the home route5) Fetch the template from w3school and put it all in an html File6) Bonnus : use static js and css file ( declare static route cf slide )7) Render a the list of todo-items from an js array8) Try to send an item to add to an non existing route ( check that it’s
not working aka 404 )9) Create a dumy procedure to handle this request and log the call10) Handle what has been sent and add it11) Try to store it into a session – ( initialise sessions at start up )12) Use session for displaying todo list items13) Generate a solution to handle the DELETE method and remove a
item from todo List14) Use ajax method ( if not already done ) 15) Be able to modify status of the item using a put request!
TP
84 Interne Orange
Create a TODO ListAcces static files
https://expressjs.com/fr/guide/
How to serve Static files :
app.use(express.static('public'));
Or more complicated :
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
And now your files are aviables : http://localhost:3000/static/images/kitten.jpg http://localhost:3000/static/css/style.css http://localhost:3000/static/js/app.js http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html
85 Interne Orange
Create a TODO List
https://expressjs.com/fr/guide/
res.redirect('/'); // redirect to page
req.session.myvar // to use session
res.json( { a: 1 } ); // to return son json
res.sendStatus( 200 ); // to send a status
res.status( 404 ).send("Sorry can't find that!") // you do command in serie
86 Interne Orange
Handle post
To use post information :
app.use(express.urlencoded({ extended: false }));
// for parsing application/jsonapp.use(bodyParser.json());
// for parsing application/xwww-app.use(bodyParser.urlencoded({ extended: true }));
// then you can access itreq.body.item
87 Interne Orange
Handle Session
var express = require('express'); var cookieParser = require('cookie-parser');var session = require('express-session'); var app = express(); app.use( cookieParser() );app.use(session({secret: "Shh, its a secret!"})); app.get( '/‘ , function(req, res){
if ( req.session.page_views ) {
req.session.page_views++; res.send("You visited this page " + req.session.page_views + " times"); }
else { req.session.page_views = 1; res.send("Welcome to this page for the first time!");
}});
app.listen(3000);
Session
88 Interne Orange
Create a TODO List
.use( function(req, res, next){ if (typeof(req.session.todolist) == 'undefined') {
req.session.todolist = []; } next();
})
89 Interne Orange
Use express-generator tool :
npm install express-generator –g
Check it’s operational :express — version
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website
90 Interne Orange
To create an app with pug engine :
express --view=pug myapp
Then you have to install all dependencies :
$ cd myapp$ npm install
To run it
( linux) : DEBUG=myapp:* npm start( win ) : SET DEBUG=myapp:* & npm start
91 Interne Orange
Bonnus : livereload :
npm install nodemon — save-dev
On ajoute une entrée au niveau de scripts dans le fichier package.json :"startd": "nodemon ./bin/www"
92 Interne Orange
Bonnus : livereload :
npm install -g nodemon
Nodemon index.js
93 Interne Orange
95 Interne Orange
How does WebSocket work ?
To establish a WebSocket connection, a specific HTTP-based handshake is exchanged between the client and the server. If successful, the application-layer protocol is "upgraded" from HTTP to WebSockets, using the previously established TCP connection. Once this occurs, HTTP is completely out of the picture; data can be sent or received using the WebSocket protocol by both endpoints, until the WebSocket connection is closed.
96 Interne Orange
var app = require('express')();var http = require('http').createServer(app);var io = require('socket.io')(http);
app.get('/', function(req, res){res.sendFile( __dirname + '/index.html');
});
io.on('connection', function(socket){console.log('a user connected');
});
http.listen(3000, function(){console.log('listening on *:3000');
});
<script src="http://localhost:3000/socket.io/socket.io.js"></script><script>var socket = io.connect('http://localhost:3000');</script>
Setup
97 Interne Orange
// …io.on( 'connection', function(socket) {
console.log('a user connected');socket.on('disconnect', function() {
console.log('user disconnected');});
});//….
Adding log off
98 Interne Orange
When sending information you can send string or JSON
socket.emit('message', { content : 'Welcome on bord ', importance: '1' } );
socket.emit('message', 'hello' );
99 Interne Orange
//…
io.on('connection', function(socket){socket.on('chat message', function(msg){
console.log('message: ' + msg);});
});
//…
<script src="/socket.io/socket.io.js"></script><script src="https://code.jquery.com/jquery-1.11.1.js"></script><script>$(function () {
$('form').submit(function(e){e.preventDefault(); // prevents page reloadingsocket.emit( ‘chat message', $('#m').val() );$('#m').val('');return false;
});</script>
Emitting events ( client to server )
100 Interne Orange
//…io.emit('some event', { someProperty: 'some value', otherProperty: 'other value' }); // This will emit the event to all connected sockets
Broadcasting events (server to client)
// In this case, for the sake of simplicity we’ll send the message to everyone, including the sender.io.on('connection', function (socket) {
socket.on('chat message', function (msg){io.emit('chat message', msg);
});});
// to send a message to everyone except for a certain emitting socketio.on('connection', function(socket){
socket.broadcast.emit('hi');});
101 Interne Orange
Broadcasting events clientside
<script>$(function () {
var socket = io();
$('form').submit( function(e){e.preventDefault(); // prevents page reloadingsocket.emit('chat message', $('#m').val());$('#m').val('');return false;
});
socket.on('chat message', function(msg){$('#messages').append($('<li>').text( msg ));
});
});</script>
102 Interne Orange
Store informations
socket.on('registernewUse', function (pseudo) {socket.nickname = pseudo;
});
// Then use it when you want :socket.on('message', function (message) {
console.log(socket.nickname + ' says : ' + message);});
103 Interne Orange
Create a ChaT
TP
104 Interne Orange
Create a ChaT
1) Try from the client to create a connection using websocket
2) Send a message from the client and read it in server
3) Send a message from the server to client and log it usingconsole.log=> Check using multiple client ( edge, FF, chrome that onlythe client receive the message )
4) Display the message in a div
5) Send a message using broadcast
TP
105 Interne Orange
Create a ChaTUsing a template
TP
106 Interne Orange
Create a ChaT
6) Use a chat template for instance :https://www.w3schools.com/howto/howto_css_chat.asphttps://bootsnipp.com/tags/chat ( need boostrap )
7) Send a Message using the template and log it on server side
8) Send the message Sent to all connected users
9) Display the list of personnes connected
10) Deal with nicknames
11) Send a message to everyone when some joining or leaving the chat.
TP
107 Interne Orange
End of the Node JS course