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

Express node js
Express node jsExpress node js
Express node js
Yashprit Singh
ย 
Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
Jesus Obenita Jr.
ย 

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

NodeJS_Presentation
NodeJS_PresentationNodeJS_Presentation
NodeJS_Presentation
Arpita Patel
ย 
Managing Patient SatLEADfor4-25-13
Managing Patient SatLEADfor4-25-13Managing Patient SatLEADfor4-25-13
Managing Patient SatLEADfor4-25-13
alfred lopez
ย 
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 Patterns
Johan Aludden
ย 

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

Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus Presentation
Ajax Experience 2009
ย 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
ย 
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 Up
David Padbury
ย 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Abhijit Gaikwad
ย 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
ย 
React Basic and Advance || React Basic
React Basic and Advance   || React BasicReact Basic and Advance   || React Basic
React Basic and Advance || React Basic
rafaqathussainc077
ย 

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
ย 
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
Ahmed 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 Code
Ahmed Assaf
ย 
Certificate_MEAN Stack Jump Start
Certificate_MEAN Stack Jump StartCertificate_MEAN Stack Jump Start
Certificate_MEAN Stack Jump Start
Ahmed 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 Code
Ahmed 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 Start
Ahmed 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

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
anilsa9823
ย 
+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
ย 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
ย 
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
9953056974 Low Rate Call Girls In Saket, Delhi NCR
ย 

Recently uploaded (20)

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 ๐Ÿ”โœ”๏ธโœ”๏ธ
ย 
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
ย 
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
ย 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
ย 
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
ย 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
ย 
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...
ย 
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
ย 
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 ...
ย 
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-...
ย 
+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...
ย 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
ย 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
ย 
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
ย 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
ย 
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
ย 
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...
ย 
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
ย 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
ย 

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