SlideShare a Scribd company logo
1 of 43
 02 | Understanding Module Design Pattern
 03 | Express.js
 Ahmed Assaf | Senior Software Engineer
Setting Expectations
 Target Audience
 Web Developers
 Web Designers
 Developers with experience using other service side languages such as PHP,
ASP.NET, Python, Ruby etc.
Module Overview
 Exports a Namespace
 Exports a Function
 Exports a Higher Order Function
 Exports a Constructor
 Exports a Singleton
 Extends a Global Object
 Applies a Monkey Patch
Module Design Patterns
 Modules are still JavaScript
 Possess many of the challenges of pre-ES6 Javascript
 Design Patterns to help with
 Encapsulation
 Stable Interface
Exports a Namespace
Exports a Namespace
 Module returns an object
 Object contains properties and functions
 Calling code can refer to properties and execute functions
Simply return an object with whatever properties and functions the
calling code should have access to
//private module stuff can happen here
//then return an object
module.exports = {
property1: 'value',
property2: 'value',
function1: function(){ … }
function2: function(){ … }
}
Core 'fs' Node module returns an object
readFile and ReadStream are functions of the returned object
Both are accessible from this calling function
Analogous to static classes and members in other languages
var fs = require('fs');
fs.readFile('./file.txt', function(err, data) {
console.log("readFile contents: '%s'", data);
});
new fs.ReadStream('./file.txt').on('data', function(data) {
console.log("ReadStream contents: '%s'", data);
});
Exports a Function
Exports a Function
 Factory function
 Gives you instancing since all variables are encased in a closure
 Closure is run for each require()
 Revealing Module Pattern you may have used in client side JavaScript
 ProTip
 If you don’t need instancing – export a namespace
 If you need instancing – export a constructor
module.exports = function(options) {
options = options || {};
var loggingLevel = options.loggingLevel || 1;
function logMessage(logLevel, message) {
if(logLevel <= loggingLevel) {
console.log(message);
}
}
return { log: logMessage };
}
DEMO
Exports a Higher Order Function
Exports a Higher Order Function
 Like the former, but also receives a function that affects the behavior of the function it returns
 Express middleware is a great example - functions are provided and the middleware function is returned
Chaining is possible with the app object because the middleware
functions each return it.
var app = require('express')();
app.use('/route1', function(res, req, next) {
//do something
next();
});
app.use('/route2', function(res, req, next) {
//do something
next();
});
Exports a Constructor
Exports a Constructor
 Constructor function creates instance
 Prototype used to define behavior
 Caller creates instance with new keyword
 Multi instance
DEMO
Exports a Singleton
Exports a Singleton
 Instantiates object before returning it
 Causes all calling modules to share a single object instance
When an object is instantiated before it's returned, it acts as a
singleton.
function Something() {
…
}
module.exports = new Something();
Mongoose is one example of a good use of the singleton pattern
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Cat = mongoose.model('Cat', { name: String });
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
if (err) // ...
console.log('meow');
});
Extends a Global Object
Extends a Global Object
 Modifies an existing type i.e. String
 Doesn’t have to export anything
 Makes for nice calling syntax but can be difficult to track down source in large project
 Frowned upon in open source packages
Applies a Monkey Patch
Applies a Monkey Patch
 A monkey patch is the dynamic modification of a class or object at runtime to fix a bug in existing code
 Similar to previous pattern (extends a global object) but affects cached node modules
The winston logger defaults all profiling statements to the info level
and you can’t change
A quick monkey patch allows you to log data out as any log level you
want and replace the built in functionality without forking the code
base
winston.Logger.prototype.profile = function(id) {
// Altered behvaior or winston loggers profile function
};
Summary
 Exports a Namespace
 Exports a Function
 Exports a Higher Order Function
 Exports a Constructor
 Exports a Singleton
 Extends a Global Object
 Applies a Monkey Patch
 03 | Express.js
What is Express?
 Express is a minimal, open source and flexible node.js web app framework designed to make developing
websites, web apps and APIs much easier.
Why use Express?
 Express helps you respond to requests with route support so that you may
write responses to specific URLs.
 Supports multiple templating engines to simplify generating HTML.
Installing and Using Express
Installing and Using Express
npm install express
npm install jade
Creating a Simple REST API
Explanation of Routes
 A router maps HTTP requests to a callback.
 HTTP requests can be sent as GET/POST/PUT/DELETE, etc.
 URLs describe the location targeted.
 Node helps you map a HTTP GET request like:
 http://localhost:8888/index
 To a request handler (callback)
app.get('/index', function (req, res) {});
Creating a Simple Express Application
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.json({message:'hooray! welcome to our api!'});
});
app.listen(process.env.PORT || 8080);
DEMO
Creating a simple REST API with Express Framework
DEMO
Using the express-generator package.
DEMO
Using Express for Multiple Pages with Query Parameters
Building a RESTful API for Dogs
Resource GET PUT POST DELETE
Collection URI, such
as
http://api.example
.com/v1/dogs/
List all
the
dogs
Replace all the dogs
with a new
collection of dogs.
Create a new
dog in the
collection.
Delete the
entire dog
collection.
Element URI, such
as
http://api.example
.com/v1/dog/1
Get a
specifi
c dog.
Replace a dog in the
collection with
another dog.
Not used.
Delete the dog
from the
collection.
DEMO
Using Express to build a RESTful API
Resources
 Express Framework http://expressjs.com/
 Intro to Express http://code.tutsplus.com/tutorials/introduction-to-express--
net-33367
 Jade Templates http://jade-lang.com/tutorial/
 JavaScript and Jade Templating
http://www.slideshare.net/wearefractal/jade-javascript-templating
Resources
 Using Node.js with Visual Studio Code
 #MVA Course By
 Stacey Mulcahy | Senior Technical Evangelist
 Rami Sayar | Technical Evangelist
 Mastering Node.js Modules #MVA Course By
 Chris Kinsman | Chief Architect at PushSpring
 https://blog.jcoglan.com/2013/03/30/callbacks-are-imperative-promises-are-functional-
nodes-biggest-missed-opportunity/
 http://code.tutsplus.com/tutorials/using-nodes-event-module--net-35941
 http://spin.atomicobject.com/2012/03/14/nodejs-and-asynchronous-programming-with-
promises/
 Github repo: https://github.com/AhmedAssaf/NodeMVA
 From : https://github.com/sayar/NodeMVA

More Related Content

What's hot

Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJSHoang Long
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Visual Engineering
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.jsEmanuele DelBono
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js SimplifiedSunil Yadav
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
Going realtime with Socket.IO
Going realtime with Socket.IOGoing realtime with Socket.IO
Going realtime with Socket.IOChristian Joudrey
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency InjectionNir Kaufman
 

What's hot (20)

Express js
Express jsExpress js
Express js
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Express node js
Express node jsExpress node js
Express node js
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Angular
AngularAngular
Angular
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
 
Going realtime with Socket.IO
Going realtime with Socket.IOGoing realtime with Socket.IO
Going realtime with Socket.IO
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
Tech Talk on ReactJS
Tech Talk on ReactJSTech Talk on ReactJS
Tech Talk on ReactJS
 

Viewers also liked

Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppEdureka!
 
Node-IL Meetup 12/2
Node-IL Meetup 12/2Node-IL Meetup 12/2
Node-IL Meetup 12/2Ynon Perek
 
Nodejs mongoose
Nodejs mongooseNodejs mongoose
Nodejs mongooseFin Chen
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsPallavi Srivastava
 
Getting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseGetting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseYnon Perek
 
Node Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js TutorialNode Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js TutorialPHP Support
 
Introduction to Node.JS Express
Introduction to Node.JS ExpressIntroduction to Node.JS Express
Introduction to Node.JS ExpressEueung Mulyana
 
EAIESB TIBCO EXPERTISE
EAIESB TIBCO EXPERTISEEAIESB TIBCO EXPERTISE
EAIESB TIBCO EXPERTISEVijay Reddy
 
NodeJS_Presentation
NodeJS_PresentationNodeJS_Presentation
NodeJS_PresentationArpita Patel
 
Mule ESB session day 1
Mule ESB session day 1Mule ESB session day 1
Mule ESB session day 1kkk_f17
 
Enterprise Integration Patterns
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration PatternsOleg Tsal-Tsalko
 
Managing Patient SatLEADfor4-25-13
Managing Patient SatLEADfor4-25-13Managing Patient SatLEADfor4-25-13
Managing Patient SatLEADfor4-25-13alfred lopez
 
Node JS Express: Steps to Create Restful Web App
Node JS Express: Steps to Create Restful Web AppNode JS Express: Steps to Create Restful Web App
Node JS Express: Steps to Create Restful Web AppEdureka!
 
Patterns for Enterprise Integration Success
Patterns for Enterprise Integration Success Patterns for Enterprise Integration Success
Patterns for Enterprise Integration Success WSO2
 
Enterprise Integration Patterns
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration PatternsJohan Aludden
 
Trends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichTrends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichAWS Germany
 
Enterprise Integration Patterns
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration PatternsSergey Podolsky
 
Mongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is BrightMongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is Brightaaronheckmann
 
Enterprise Integration Patterns Revisited (again) for the Era of Big Data, In...
Enterprise Integration Patterns Revisited (again) for the Era of Big Data, In...Enterprise Integration Patterns Revisited (again) for the Era of Big Data, In...
Enterprise Integration Patterns Revisited (again) for the Era of Big Data, In...Kai Wähner
 

Viewers also liked (20)

Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web App
 
Node-IL Meetup 12/2
Node-IL Meetup 12/2Node-IL Meetup 12/2
Node-IL Meetup 12/2
 
Nodejs mongoose
Nodejs mongooseNodejs mongoose
Nodejs mongoose
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node js
 
Getting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseGetting Started With MongoDB and Mongoose
Getting Started With MongoDB and Mongoose
 
Node Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js TutorialNode Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js Tutorial
 
Introduction to Node.JS Express
Introduction to Node.JS ExpressIntroduction to Node.JS Express
Introduction to Node.JS Express
 
EAIESB TIBCO EXPERTISE
EAIESB TIBCO EXPERTISEEAIESB TIBCO EXPERTISE
EAIESB TIBCO EXPERTISE
 
Express JS
Express JSExpress JS
Express JS
 
NodeJS_Presentation
NodeJS_PresentationNodeJS_Presentation
NodeJS_Presentation
 
Mule ESB session day 1
Mule ESB session day 1Mule ESB session day 1
Mule ESB session day 1
 
Enterprise Integration Patterns
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration Patterns
 
Managing Patient SatLEADfor4-25-13
Managing Patient SatLEADfor4-25-13Managing Patient SatLEADfor4-25-13
Managing Patient SatLEADfor4-25-13
 
Node JS Express: Steps to Create Restful Web App
Node JS Express: Steps to Create Restful Web AppNode JS Express: Steps to Create Restful Web App
Node JS Express: Steps to Create Restful Web App
 
Patterns for Enterprise Integration Success
Patterns for Enterprise Integration Success Patterns for Enterprise Integration Success
Patterns for Enterprise Integration Success
 
Enterprise Integration Patterns
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration Patterns
 
Trends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichTrends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science Bereich
 
Enterprise Integration Patterns
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration Patterns
 
Mongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is BrightMongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is Bright
 
Enterprise Integration Patterns Revisited (again) for the Era of Big Data, In...
Enterprise Integration Patterns Revisited (again) for the Era of Big Data, In...Enterprise Integration Patterns Revisited (again) for the Era of Big Data, In...
Enterprise Integration Patterns Revisited (again) for the Era of Big Data, In...
 

Similar to Module design pattern i.e. express js

Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsSrikanth Shenoy
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationAjax Experience 2009
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
IBM ConnectED 2015 - MAS103 XPages Performance and Scalability
IBM ConnectED 2015 - MAS103 XPages Performance and ScalabilityIBM ConnectED 2015 - MAS103 XPages Performance and Scalability
IBM ConnectED 2015 - MAS103 XPages Performance and ScalabilityPaul Withers
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsSebastian Springer
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
Sencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScriptSencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScriptRohan Chandane
 
Workflow Management with Espresso Workflow
Workflow Management with Espresso WorkflowWorkflow Management with Espresso Workflow
Workflow Management with Espresso WorkflowRolf Kremer
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play frameworkFelipe
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Gaurav Behere
 
React Basic and Advance || React Basic
React Basic and Advance   || React BasicReact Basic and Advance   || React Basic
React Basic and Advance || React Basicrafaqathussainc077
 

Similar to Module design pattern i.e. express js (20)

Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus Presentation
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
IBM ConnectED 2015 - MAS103 XPages Performance and Scalability
IBM ConnectED 2015 - MAS103 XPages Performance and ScalabilityIBM ConnectED 2015 - MAS103 XPages Performance and Scalability
IBM ConnectED 2015 - MAS103 XPages Performance and Scalability
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.js
 
React native
React nativeReact native
React native
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Sencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScriptSencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScript
 
Workflow Management with Espresso Workflow
Workflow Management with Espresso WorkflowWorkflow Management with Espresso Workflow
Workflow Management with Espresso Workflow
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !
 
React Basic and Advance || React Basic
React Basic and Advance   || React BasicReact Basic and Advance   || React Basic
React Basic and Advance || React Basic
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
Modern frontend in react.js
Modern frontend in react.jsModern frontend in react.js
Modern frontend in react.js
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 

More from Ahmed Assaf

Javascript Road Trip(ES6)
Javascript Road Trip(ES6)Javascript Road Trip(ES6)
Javascript Road Trip(ES6)Ahmed Assaf
 
Javascript Road Trip(es6)
Javascript Road Trip(es6)Javascript Road Trip(es6)
Javascript Road Trip(es6)Ahmed Assaf
 
Introduction to node.js By Ahmed Assaf
Introduction to node.js  By Ahmed AssafIntroduction to node.js  By Ahmed Assaf
Introduction to node.js By Ahmed AssafAhmed Assaf
 
Certificate_Building Apps with Node.js Jump Start
Certificate_Building Apps with Node.js Jump StartCertificate_Building Apps with Node.js Jump Start
Certificate_Building Apps with Node.js Jump StartAhmed Assaf
 
Certificate_Using Node.js with Visual Studio Code
Certificate_Using Node.js with Visual Studio CodeCertificate_Using Node.js with Visual Studio Code
Certificate_Using Node.js with Visual Studio CodeAhmed Assaf
 
Certificate_MEAN Stack Jump Start
Certificate_MEAN Stack Jump StartCertificate_MEAN Stack Jump Start
Certificate_MEAN Stack Jump StartAhmed Assaf
 
Certificate_Mastering Node.js Modules and Packages with Visual Studio Code
Certificate_Mastering Node.js Modules and Packages with Visual Studio CodeCertificate_Mastering Node.js Modules and Packages with Visual Studio Code
Certificate_Mastering Node.js Modules and Packages with Visual Studio CodeAhmed Assaf
 
Certificate_Developing in HTML5 with JavaScript and CSS3 Jump Start
Certificate_Developing in HTML5 with JavaScript and CSS3 Jump StartCertificate_Developing in HTML5 with JavaScript and CSS3 Jump Start
Certificate_Developing in HTML5 with JavaScript and CSS3 Jump StartAhmed Assaf
 

More from Ahmed Assaf (8)

Javascript Road Trip(ES6)
Javascript Road Trip(ES6)Javascript Road Trip(ES6)
Javascript Road Trip(ES6)
 
Javascript Road Trip(es6)
Javascript Road Trip(es6)Javascript Road Trip(es6)
Javascript Road Trip(es6)
 
Introduction to node.js By Ahmed Assaf
Introduction to node.js  By Ahmed AssafIntroduction to node.js  By Ahmed Assaf
Introduction to node.js By Ahmed Assaf
 
Certificate_Building Apps with Node.js Jump Start
Certificate_Building Apps with Node.js Jump StartCertificate_Building Apps with Node.js Jump Start
Certificate_Building Apps with Node.js Jump Start
 
Certificate_Using Node.js with Visual Studio Code
Certificate_Using Node.js with Visual Studio CodeCertificate_Using Node.js with Visual Studio Code
Certificate_Using Node.js with Visual Studio Code
 
Certificate_MEAN Stack Jump Start
Certificate_MEAN Stack Jump StartCertificate_MEAN Stack Jump Start
Certificate_MEAN Stack Jump Start
 
Certificate_Mastering Node.js Modules and Packages with Visual Studio Code
Certificate_Mastering Node.js Modules and Packages with Visual Studio CodeCertificate_Mastering Node.js Modules and Packages with Visual Studio Code
Certificate_Mastering Node.js Modules and Packages with Visual Studio Code
 
Certificate_Developing in HTML5 with JavaScript and CSS3 Jump Start
Certificate_Developing in HTML5 with JavaScript and CSS3 Jump StartCertificate_Developing in HTML5 with JavaScript and CSS3 Jump Start
Certificate_Developing in HTML5 with JavaScript and CSS3 Jump Start
 

Recently uploaded

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 

Recently uploaded (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

Module design pattern i.e. express js

  • 1.  02 | Understanding Module Design Pattern  03 | Express.js  Ahmed Assaf | Senior Software Engineer
  • 2. Setting Expectations  Target Audience  Web Developers  Web Designers  Developers with experience using other service side languages such as PHP, ASP.NET, Python, Ruby etc.
  • 3. Module Overview  Exports a Namespace  Exports a Function  Exports a Higher Order Function  Exports a Constructor  Exports a Singleton  Extends a Global Object  Applies a Monkey Patch
  • 4. Module Design Patterns  Modules are still JavaScript  Possess many of the challenges of pre-ES6 Javascript  Design Patterns to help with  Encapsulation  Stable Interface
  • 6. Exports a Namespace  Module returns an object  Object contains properties and functions  Calling code can refer to properties and execute functions
  • 7. Simply return an object with whatever properties and functions the calling code should have access to //private module stuff can happen here //then return an object module.exports = { property1: 'value', property2: 'value', function1: function(){ … } function2: function(){ … } }
  • 8. Core 'fs' Node module returns an object readFile and ReadStream are functions of the returned object Both are accessible from this calling function Analogous to static classes and members in other languages var fs = require('fs'); fs.readFile('./file.txt', function(err, data) { console.log("readFile contents: '%s'", data); }); new fs.ReadStream('./file.txt').on('data', function(data) { console.log("ReadStream contents: '%s'", data); });
  • 10. Exports a Function  Factory function  Gives you instancing since all variables are encased in a closure  Closure is run for each require()  Revealing Module Pattern you may have used in client side JavaScript  ProTip  If you don’t need instancing – export a namespace  If you need instancing – export a constructor
  • 11. module.exports = function(options) { options = options || {}; var loggingLevel = options.loggingLevel || 1; function logMessage(logLevel, message) { if(logLevel <= loggingLevel) { console.log(message); } } return { log: logMessage }; }
  • 12. DEMO
  • 13. Exports a Higher Order Function
  • 14. Exports a Higher Order Function  Like the former, but also receives a function that affects the behavior of the function it returns  Express middleware is a great example - functions are provided and the middleware function is returned
  • 15. Chaining is possible with the app object because the middleware functions each return it. var app = require('express')(); app.use('/route1', function(res, req, next) { //do something next(); }); app.use('/route2', function(res, req, next) { //do something next(); });
  • 17. Exports a Constructor  Constructor function creates instance  Prototype used to define behavior  Caller creates instance with new keyword  Multi instance
  • 18. DEMO
  • 20. Exports a Singleton  Instantiates object before returning it  Causes all calling modules to share a single object instance
  • 21. When an object is instantiated before it's returned, it acts as a singleton. function Something() { … } module.exports = new Something();
  • 22. Mongoose is one example of a good use of the singleton pattern var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var Cat = mongoose.model('Cat', { name: String }); var kitty = new Cat({ name: 'Zildjian' }); kitty.save(function (err) { if (err) // ... console.log('meow'); });
  • 24. Extends a Global Object  Modifies an existing type i.e. String  Doesn’t have to export anything  Makes for nice calling syntax but can be difficult to track down source in large project  Frowned upon in open source packages
  • 26. Applies a Monkey Patch  A monkey patch is the dynamic modification of a class or object at runtime to fix a bug in existing code  Similar to previous pattern (extends a global object) but affects cached node modules
  • 27. The winston logger defaults all profiling statements to the info level and you can’t change A quick monkey patch allows you to log data out as any log level you want and replace the built in functionality without forking the code base winston.Logger.prototype.profile = function(id) { // Altered behvaior or winston loggers profile function };
  • 28. Summary  Exports a Namespace  Exports a Function  Exports a Higher Order Function  Exports a Constructor  Exports a Singleton  Extends a Global Object  Applies a Monkey Patch
  • 29.  03 | Express.js
  • 30. What is Express?  Express is a minimal, open source and flexible node.js web app framework designed to make developing websites, web apps and APIs much easier.
  • 31. Why use Express?  Express helps you respond to requests with route support so that you may write responses to specific URLs.  Supports multiple templating engines to simplify generating HTML.
  • 33. Installing and Using Express npm install express npm install jade
  • 34. Creating a Simple REST API
  • 35. Explanation of Routes  A router maps HTTP requests to a callback.  HTTP requests can be sent as GET/POST/PUT/DELETE, etc.  URLs describe the location targeted.  Node helps you map a HTTP GET request like:  http://localhost:8888/index  To a request handler (callback) app.get('/index', function (req, res) {});
  • 36. Creating a Simple Express Application var express = require('express'); var app = express(); app.get('/', function (req, res) { res.json({message:'hooray! welcome to our api!'}); }); app.listen(process.env.PORT || 8080);
  • 37. DEMO Creating a simple REST API with Express Framework
  • 39. DEMO Using Express for Multiple Pages with Query Parameters
  • 40. Building a RESTful API for Dogs Resource GET PUT POST DELETE Collection URI, such as http://api.example .com/v1/dogs/ List all the dogs Replace all the dogs with a new collection of dogs. Create a new dog in the collection. Delete the entire dog collection. Element URI, such as http://api.example .com/v1/dog/1 Get a specifi c dog. Replace a dog in the collection with another dog. Not used. Delete the dog from the collection.
  • 41. DEMO Using Express to build a RESTful API
  • 42. Resources  Express Framework http://expressjs.com/  Intro to Express http://code.tutsplus.com/tutorials/introduction-to-express-- net-33367  Jade Templates http://jade-lang.com/tutorial/  JavaScript and Jade Templating http://www.slideshare.net/wearefractal/jade-javascript-templating
  • 43. Resources  Using Node.js with Visual Studio Code  #MVA Course By  Stacey Mulcahy | Senior Technical Evangelist  Rami Sayar | Technical Evangelist  Mastering Node.js Modules #MVA Course By  Chris Kinsman | Chief Architect at PushSpring  https://blog.jcoglan.com/2013/03/30/callbacks-are-imperative-promises-are-functional- nodes-biggest-missed-opportunity/  http://code.tutsplus.com/tutorials/using-nodes-event-module--net-35941  http://spin.atomicobject.com/2012/03/14/nodejs-and-asynchronous-programming-with- promises/  Github repo: https://github.com/AhmedAssaf/NodeMVA  From : https://github.com/sayar/NodeMVA

Editor's Notes

  1. 1
  2. After this slide, it’s all demo. See the demo script for the majority of the content
  3. ~7 min
  4. ~7 min
  5. ~7 min
  6. ~7 min
  7. ~7 min
  8. ~7 min
  9. ~7 min
  10. After this slide, it’s all demo. See the demo script for the majority of the content
  11. 29
  12. 32
  13. 34
  14. npm install -g express-generator express /tmp/foo