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

What's hot (20)

Detecting headless browsers
Detecting headless browsersDetecting headless browsers
Detecting headless browsers
 
Node.js введение в технологию, КПИ #ITmeetingKPI
Node.js введение в технологию, КПИ  #ITmeetingKPINode.js введение в технологию, КПИ  #ITmeetingKPI
Node.js введение в технологию, КПИ #ITmeetingKPI
 
Javascript Arrow function
Javascript Arrow functionJavascript Arrow function
Javascript Arrow function
 
File system node js
File system node jsFile system node js
File system node js
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
React state
React  stateReact  state
React state
 
React lecture
React lectureReact lecture
React lecture
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
JSON and REST
JSON and RESTJSON and REST
JSON and REST
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
jQuery
jQueryjQuery
jQuery
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
Puppeteer can automate that! - Frontmania
Puppeteer can automate that! - FrontmaniaPuppeteer can automate that! - Frontmania
Puppeteer can automate that! - Frontmania
 

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
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 

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
 
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

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

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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Recently uploaded (20)

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
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
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
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
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 ...
 
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
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
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
 
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
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
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 🔝✔️✔️
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
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
 
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
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

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