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 (20)

Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
Clean code
Clean codeClean code
Clean code
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
An Intro into webpack
An Intro into webpackAn Intro into webpack
An Intro into webpack
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
Webpack Introduction
Webpack IntroductionWebpack Introduction
Webpack Introduction
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Socket.IO
Socket.IOSocket.IO
Socket.IO
 
React js
React jsReact js
React js
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
ReactJS
ReactJSReactJS
ReactJS
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Swagger UI
Swagger UISwagger UI
Swagger UI
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfiJava entreprise edition et industrialisation du génie logiciel par m.youssfi
Java entreprise edition et industrialisation du génie logiciel par m.youssfi
 

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 Express.js Module Design Patterns

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 Express.js Module Design Patterns (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
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
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
 

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

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
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
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
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
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
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
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
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 

Recently uploaded (20)

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...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
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
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
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...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
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
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 

Express.js Module Design Patterns

  • 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