Module design pattern i.e. express js

Ahmed Assaf
Ahmed AssafSenior Software Engineer in .NET at ITWORX Education | MEAN Stack Developer | PhoneGap Mobile Apps
 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
1 of 43

Recommended

Express js by
Express jsExpress js
Express jsManav Prasad
6.6K views19 slides
Introduction to React JS for beginners by
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
4.2K views21 slides
ES6 presentation by
ES6 presentationES6 presentation
ES6 presentationritika1
564 views18 slides
Unit 1 - TypeScript & Introduction to Angular CLI.pptx by
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxMalla Reddy University
447 views55 slides
Introduction to React JS by
Introduction to React JSIntroduction to React JS
Introduction to React JSBethmi Gunasekara
422 views31 slides
Rxjs ppt by
Rxjs pptRxjs ppt
Rxjs pptChristoffer Noring
3.7K views78 slides

More Related Content

What's hot

The New JavaScript: ES6 by
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6Rob Eisenberg
4K views23 slides
ReactJS by
ReactJSReactJS
ReactJSHiten Pratap Singh
270 views18 slides
Intro to React by
Intro to ReactIntro to React
Intro to ReactEric Westfall
2.1K views28 slides
Nodejs functions & modules by
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modulesmonikadeshmane
141 views29 slides
React Router: React Meetup XXL by
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXLRob Gietema
2.3K views76 slides
React Js Simplified by
React Js SimplifiedReact Js Simplified
React Js SimplifiedSunil Yadav
344 views30 slides

What's hot(20)

React Router: React Meetup XXL by Rob Gietema
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
Rob Gietema2.3K views
React Js Simplified by Sunil Yadav
React Js SimplifiedReact Js Simplified
React Js Simplified
Sunil Yadav344 views
Basics of React Hooks.pptx.pdf by Knoldus Inc.
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
Knoldus Inc.1.3K views
Advanced Javascript by Adieu
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu8.2K views
React.js - The Dawn of Virtual DOM by Jimit Shah
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOM
Jimit Shah1.4K views
Introduction to Javascript by Amit Tyagi
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi13.5K views
[Final] ReactJS presentation by 洪 鹏发
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发30.2K views
Introduction to ReactJS by Knoldus Inc.
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
Knoldus Inc.2.3K views
TypeScript Introduction by Dmitry Sheiko
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko7.4K views

Viewers also liked

Node JS Express : Steps to Create Restful Web App by
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!
3.2K views25 slides
Node-IL Meetup 12/2 by
Node-IL Meetup 12/2Node-IL Meetup 12/2
Node-IL Meetup 12/2Ynon Perek
1.2K views51 slides
Nodejs mongoose by
Nodejs mongooseNodejs mongoose
Nodejs mongooseFin Chen
1.9K views16 slides
Mongoose getting started-Mongo Db with Node js by
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsPallavi Srivastava
1.3K views15 slides
Getting Started With MongoDB and Mongoose by
Getting Started With MongoDB and MongooseGetting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseYnon Perek
17K views109 slides
Node Js, AngularJs and Express Js Tutorial by
Node Js, AngularJs and Express Js TutorialNode Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js TutorialPHP Support
1.3K views10 slides

Viewers also liked(20)

Node JS Express : Steps to Create Restful Web App by Edureka!
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
Edureka!3.2K views
Node-IL Meetup 12/2 by Ynon Perek
Node-IL Meetup 12/2Node-IL Meetup 12/2
Node-IL Meetup 12/2
Ynon Perek1.2K views
Nodejs mongoose by Fin Chen
Nodejs mongooseNodejs mongoose
Nodejs mongoose
Fin Chen1.9K views
Mongoose getting started-Mongo Db with Node js by Pallavi Srivastava
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node js
Pallavi Srivastava1.3K views
Getting Started With MongoDB and Mongoose by Ynon Perek
Getting Started With MongoDB and MongooseGetting Started With MongoDB and Mongoose
Getting Started With MongoDB and Mongoose
Ynon Perek17K views
Node Js, AngularJs and Express Js Tutorial by PHP Support
Node Js, AngularJs and Express Js TutorialNode Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js Tutorial
PHP Support1.3K views
Introduction to Node.JS Express by Eueung Mulyana
Introduction to Node.JS ExpressIntroduction to Node.JS Express
Introduction to Node.JS Express
Eueung Mulyana754 views
EAIESB TIBCO EXPERTISE by Vijay Reddy
EAIESB TIBCO EXPERTISEEAIESB TIBCO EXPERTISE
EAIESB TIBCO EXPERTISE
Vijay Reddy375 views
Express JS by Alok Guha
Express JSExpress JS
Express JS
Alok Guha2.5K views
Mule ESB session day 1 by kkk_f17
Mule ESB session day 1Mule ESB session day 1
Mule ESB session day 1
kkk_f171.3K views
Managing Patient SatLEADfor4-25-13 by alfred lopez
Managing Patient SatLEADfor4-25-13Managing Patient SatLEADfor4-25-13
Managing Patient SatLEADfor4-25-13
alfred lopez203 views
Node JS Express: Steps to Create Restful Web App by Edureka!
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
Edureka!2.2K views
Patterns for Enterprise Integration Success by WSO2
Patterns for Enterprise Integration Success Patterns for Enterprise Integration Success
Patterns for Enterprise Integration Success
WSO22.3K views
Enterprise Integration Patterns by Johan Aludden
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration Patterns
Johan Aludden4.8K views
Trends und Anwendungsbeispiele im Life Science Bereich by AWS Germany
Trends und Anwendungsbeispiele im Life Science BereichTrends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science Bereich
AWS Germany557 views
Enterprise Integration Patterns by Sergey Podolsky
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration Patterns
Sergey Podolsky2.7K views
Mongoose v3 :: The Future is Bright by aaronheckmann
Mongoose v3 :: The Future is BrightMongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is Bright
aaronheckmann14.1K views
Enterprise Integration Patterns Revisited (again) for the Era of Big Data, In... by Kai Wähner
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ähner8.2K views

Similar to Module design pattern i.e. express js

Effective JavaFX architecture with FxObjects by
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsSrikanth Shenoy
2K views28 slides
Laurens Van Den Oever Xopus Presentation by
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationAjax Experience 2009
1.4K views39 slides
Smoothing Your Java with DSLs by
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
1.1K views39 slides
WebNet Conference 2012 - Designing complex applications using html5 and knock... by
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
1.6K views36 slides
[2015/2016] JavaScript by
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScriptIvano Malavolta
717 views86 slides
JavaScript Growing Up by
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
14.1K views57 slides

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

Effective JavaFX architecture with FxObjects by Srikanth Shenoy
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
Srikanth Shenoy2K views
Smoothing Your Java with DSLs by intelliyole
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole1.1K views
WebNet Conference 2012 - Designing complex applications using html5 and knock... by Fabio Franzini
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 Franzini1.6K views
JavaScript Growing Up by David Padbury
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury14.1K views
IBM ConnectED 2015 - MAS103 XPages Performance and Scalability by Paul Withers
IBM ConnectED 2015 - MAS103 XPages Performance and ScalabilityIBM ConnectED 2015 - MAS103 XPages Performance and Scalability
IBM ConnectED 2015 - MAS103 XPages Performance and Scalability
Paul Withers3.3K views
Divide and Conquer – Microservices with Node.js by Sebastian Springer
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.js
Sebastian Springer2.3K views
Build Web Apps using Node.js by davidchubbs
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs675 views
Sencha / ExtJS : Object Oriented JavaScript by Rohan Chandane
Sencha / ExtJS : Object Oriented JavaScriptSencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScript
Rohan Chandane16.8K views
Workflow Management with Espresso Workflow by Rolf Kremer
Workflow Management with Espresso WorkflowWorkflow Management with Espresso Workflow
Workflow Management with Espresso Workflow
Rolf Kremer1.7K views
Short intro to scala and the play framework by Felipe
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
Felipe 1.7K views
Intro to ES6 and why should you bother ! by Gaurav Behere
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 Behere550 views

More from Ahmed Assaf

Javascript Road Trip(ES6) by
Javascript Road Trip(ES6)Javascript Road Trip(ES6)
Javascript Road Trip(ES6)Ahmed Assaf
93 views12 slides
Javascript Road Trip(es6) by
Javascript Road Trip(es6)Javascript Road Trip(es6)
Javascript Road Trip(es6)Ahmed Assaf
322 views12 slides
Introduction to node.js By Ahmed Assaf by
Introduction to node.js  By Ahmed AssafIntroduction to node.js  By Ahmed Assaf
Introduction to node.js By Ahmed AssafAhmed Assaf
198 views41 slides
Certificate_Building Apps with Node.js Jump Start by
Certificate_Building Apps with Node.js Jump StartCertificate_Building Apps with Node.js Jump Start
Certificate_Building Apps with Node.js Jump StartAhmed Assaf
86 views1 slide
Certificate_Using Node.js with Visual Studio Code by
Certificate_Using Node.js with Visual Studio CodeCertificate_Using Node.js with Visual Studio Code
Certificate_Using Node.js with Visual Studio CodeAhmed Assaf
87 views1 slide
Certificate_MEAN Stack Jump Start by
Certificate_MEAN Stack Jump StartCertificate_MEAN Stack Jump Start
Certificate_MEAN Stack Jump StartAhmed Assaf
86 views1 slide

More from Ahmed Assaf(8)

Javascript Road Trip(ES6) by Ahmed Assaf
Javascript Road Trip(ES6)Javascript Road Trip(ES6)
Javascript Road Trip(ES6)
Ahmed Assaf93 views
Javascript Road Trip(es6) by Ahmed Assaf
Javascript Road Trip(es6)Javascript Road Trip(es6)
Javascript Road Trip(es6)
Ahmed Assaf322 views
Introduction to node.js By Ahmed Assaf by Ahmed Assaf
Introduction to node.js  By Ahmed AssafIntroduction to node.js  By Ahmed Assaf
Introduction to node.js By Ahmed Assaf
Ahmed Assaf198 views
Certificate_Building Apps with Node.js Jump Start by Ahmed Assaf
Certificate_Building Apps with Node.js Jump StartCertificate_Building Apps with Node.js Jump Start
Certificate_Building Apps with Node.js Jump Start
Ahmed Assaf86 views
Certificate_Using Node.js with Visual Studio Code by Ahmed Assaf
Certificate_Using Node.js with Visual Studio CodeCertificate_Using Node.js with Visual Studio Code
Certificate_Using Node.js with Visual Studio Code
Ahmed Assaf87 views
Certificate_MEAN Stack Jump Start by Ahmed Assaf
Certificate_MEAN Stack Jump StartCertificate_MEAN Stack Jump Start
Certificate_MEAN Stack Jump Start
Ahmed Assaf86 views
Certificate_Mastering Node.js Modules and Packages with Visual Studio Code by Ahmed Assaf
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 Assaf125 views
Certificate_Developing in HTML5 with JavaScript and CSS3 Jump Start by Ahmed Assaf
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 Assaf161 views

Recently uploaded

SUGCON ANZ Presentation V2.1 Final.pptx by
SUGCON ANZ Presentation V2.1 Final.pptxSUGCON ANZ Presentation V2.1 Final.pptx
SUGCON ANZ Presentation V2.1 Final.pptxJack Spektor
22 views34 slides
Tridens DevOps by
Tridens DevOpsTridens DevOps
Tridens DevOpsTridens
9 views28 slides
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ... by
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...Deltares
9 views32 slides
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - Parker by
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - ParkerDSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - Parker
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - ParkerDeltares
9 views16 slides
Advanced API Mocking Techniques by
Advanced API Mocking TechniquesAdvanced API Mocking Techniques
Advanced API Mocking TechniquesDimpy Adhikary
19 views11 slides
Unleash The Monkeys by
Unleash The MonkeysUnleash The Monkeys
Unleash The MonkeysJacob Duijzer
7 views28 slides

Recently uploaded(20)

SUGCON ANZ Presentation V2.1 Final.pptx by Jack Spektor
SUGCON ANZ Presentation V2.1 Final.pptxSUGCON ANZ Presentation V2.1 Final.pptx
SUGCON ANZ Presentation V2.1 Final.pptx
Jack Spektor22 views
Tridens DevOps by Tridens
Tridens DevOpsTridens DevOps
Tridens DevOps
Tridens9 views
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ... by Deltares
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...
Deltares9 views
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - Parker by Deltares
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - ParkerDSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - Parker
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - Parker
Deltares9 views
Advanced API Mocking Techniques by Dimpy Adhikary
Advanced API Mocking TechniquesAdvanced API Mocking Techniques
Advanced API Mocking Techniques
Dimpy Adhikary19 views
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema by Deltares
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
Deltares17 views
Cycleops - Automate deployments on top of bare metal.pptx by Thanassis Parathyras
Cycleops - Automate deployments on top of bare metal.pptxCycleops - Automate deployments on top of bare metal.pptx
Cycleops - Automate deployments on top of bare metal.pptx
DSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - Prida by Deltares
DSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - PridaDSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - Prida
DSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - Prida
Deltares18 views
Upgrading Incident Management with Icinga - Icinga Camp Milan 2023 by Icinga
Upgrading Incident Management with Icinga - Icinga Camp Milan 2023Upgrading Incident Management with Icinga - Icinga Camp Milan 2023
Upgrading Incident Management with Icinga - Icinga Camp Milan 2023
Icinga38 views
Software testing company in India.pptx by SakshiPatel82
Software testing company in India.pptxSoftware testing company in India.pptx
Software testing company in India.pptx
SakshiPatel827 views
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J... by Deltares
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
DSD-INT 2023 3D hydrodynamic modelling of microplastic transport in lakes - J...
Deltares9 views
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports by Ra'Fat Al-Msie'deen
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsBushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
A first look at MariaDB 11.x features and ideas on how to use them by Federico Razzoli
A first look at MariaDB 11.x features and ideas on how to use themA first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use them
Federico Razzoli45 views
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)... by Deltares
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
Deltares9 views
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut... by HCLSoftware
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...
HCLSoftware6 views
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by Donato Onofri
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Donato Onofri711 views

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