SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
JAVASCRIPT: THE
         IMPORTANT BITS
REVIEWING JAVASCRIPT AND JQUERY FUNDAMENTALS AS WELL AS A
                   BRIEF INTRO TO NODEJS
THINK YOU KNOW JAVASCRIPT?
     typeof [] === "array"; false
     0.1 + 0.2 === 0.3; false
     a === null; false
     0 == '0'; true
     1 == '1'; true
     '' == '0'; false
     '' == 0; true
     'false' == false; false

          True or false?
THINK YOU KNOW JAVASCRIPT?
return
{
  a: "hello"
}



                What does this return?
THINK YOU KNOW JAVASCRIPT?
LET'S GET STARTED WITH THE BASICS.
VARIABLES
When declairing a variable without the "var", it puts the variable in
             global space which can be problematic.


   function hello() {
     test1 = 'hello';        // global scope
     var test2 = 'hello2';   // this function scope
   }

   hello();

   console.log(test1); // 'hello';
   console.log(test2); // undefined
SCOPING
       There is no block scoping, only function scoping:
for (var i = 0; i < 10; i++) {
  console.log(i);
}
console.log(i); // prints 10



       If you want to block the scope of the above loop:
(function () {
  for (var i = 0; i < 10; i++) {
    console.log(i);
  }
}());
var i;
console.log(i); // undefined
SCOPE IN CALLBACKS
In callbacks, you can share variables from the parent function:
 var obj = {
   objValue: 'hello',
   test: function() {
     var self = this;
       setTimeout(function() {
         console.log(this.objValue); // undefined
         console.log(self.objValue); // 'hello'
       }, 10);
   }
 }
OBJECTS AND "CLASSES"
Objects are like JSON with some class aspects known as
                      prototypes.
OBJECTS AND "CLASSES"
                            An example class:


Animal = (function() {

  function Animal(name) {
    this.name = name;
  }

  Animal.prototype.move = function() {
     return alert(this.name + ' moved.');
  };

  return Animal;

}());
COMMON JAVASCRIPT PATTERNS
IMMEDIATE EXECUTION FUNCTION
(function() {
  // Your logic here
}());



This immediately executes your logic as anonymous scope.
PRIVATE PATTERN
 var getCount = function() {
   var count = 0;
   return function() {
       return ++count;
   }
 }
 var next = getCount();
 console.log(next()); // 1
 console.log(next()); // 2



This pattern allows you to expose only what you want exposed.
INITIALIZATION
                        Variable initialization:
var value = value || 'somevalue';



                   Complex object initialization:
({
  val1: 1,
  val2: null,
  init: function() {
    this.val2 = 2;
    return this;
  }
}).init();
LET'S GO OVER JQUERY OPTIMIZATION.
SELECTOR CACHING
                                    Bad:
$('.someclass').text('replace some text.');
$('.someclass').css('color', 'red');
$('.someclass').focus();



                                   Good:
$('.someclass')
  .text('replace some text.')
  .css('color', 'red')
  .focus();
SELECTOR CACHING
                       Caching with callbacks.
var $someotherclass = $('.someotherclass');
$('.someclass').on('click', function(e) {
  $someotherclass.text('some event');
});



                             Caching "this":
$('.someclass').on('click', function(e)) {
  $this = $(this);
  $this.text('something');
  $this.hide();
});
EVENT ATTACHING
        When attaching events, use the "on" function.
$('a').on('click', function(e)) {
  console.log('A link was clicked.');
});



           What about dynamically generated links?
$(document).on('click', 'a', function(e)) {
  console.log('A link was clicked.');
});
PROPERLY STOPPING EVENTS
           Returning false is not always a good thing:
$('a').on('click', function(e) {
  console.log('Stopping propagation.');
  return false;
  // Same as:
  // e.preventDefault();
  // e.stopPropagation();
});
$('a').on('click', function(e)) {
  console.log('Another click.');
  // Never gets called because of the
  // return false in the above event.
});
BASIC JQUERY PLUGIN STRUCTURE
(function($) {
  $.fn.myLog = function() {
        return this.each(function() {
                console.log($(this));
        });
  }
}(jQuery));



                                  Usage:
$('p').myLog();
INTRODUCTION TO NODEJS
Nodejs is an event-driven language built on Google's V8 (in c).

It's package manager is known as npm and is now packaged with
                            nodejs.
NODEJS: HELLO WORLD
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Worldn');
}).listen(1337);
console.log('Server running on port 1337');


                        Source:   http://nodejs.org/about/
NODEJS: DEPENDANCY MANAGEMENT
You can manage dependencies for your nodejs app in package.json:
   {
       "name": "sample-app",
       "version": "0.0.1",
       "dependencies": {
         "express": "2.5.x"
       }
   }




   This allows us to install our project dependencies with npm:
   npm install
NODEJS: EXPRESS SERVER
               Our hello world example in express:
var express = require('express');
app = express.createServer()
app.get('/', function(req, res) {
  res.send('Hello World');
});
app.listen(1337);
console.log('Listening on port 1337');
NODEJS: CONNECT MIDDLEWARE
Routing middleware is anything that implements the request,
           response, and next function pattern.
// Request logger
function logger(req, res, next) {
  console.log("Path requested: " + req.path);
  next();
}




                        Using this middleware:
app.get('/', logger, function(req, res) {
  res.send('Hello World');
});
QUESTIONS?
Javascript: the important bits

Contenu connexe

Tendances

Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
Alok Guha
 

Tendances (20)

JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
JavaScript Basics and Trends
JavaScript Basics and TrendsJavaScript Basics and Trends
JavaScript Basics and Trends
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Deferred
DeferredDeferred
Deferred
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Map kit light
Map kit lightMap kit light
Map kit light
 

En vedette (18)

Observe, Question, Design.
Observe, Question, Design.Observe, Question, Design.
Observe, Question, Design.
 
Ghost recon
Ghost reconGhost recon
Ghost recon
 
Inbound 2012 Square 2 Marketing Presentation v2
Inbound 2012 Square 2 Marketing Presentation v2Inbound 2012 Square 2 Marketing Presentation v2
Inbound 2012 Square 2 Marketing Presentation v2
 
mengenal tajwid
mengenal tajwidmengenal tajwid
mengenal tajwid
 
Major1 week2 presentation
Major1 week2 presentationMajor1 week2 presentation
Major1 week2 presentation
 
Study Case: Black Swan
Study Case: Black SwanStudy Case: Black Swan
Study Case: Black Swan
 
Press Complaints Commission
Press Complaints CommissionPress Complaints Commission
Press Complaints Commission
 
Classification
ClassificationClassification
Classification
 
War in the middle east powerpoint
War in the middle east powerpointWar in the middle east powerpoint
War in the middle east powerpoint
 
Observe. Question. Design
Observe. Question. Design Observe. Question. Design
Observe. Question. Design
 
Mengenal jaringan internet 2
Mengenal jaringan internet 2Mengenal jaringan internet 2
Mengenal jaringan internet 2
 
Simple Storyboard
Simple StoryboardSimple Storyboard
Simple Storyboard
 
Squishy[1]
Squishy[1]Squishy[1]
Squishy[1]
 
Webiste plan1
Webiste plan1Webiste plan1
Webiste plan1
 
Advertisment..
Advertisment..Advertisment..
Advertisment..
 
Audit:2
Audit:2Audit:2
Audit:2
 
Mengenal khat
Mengenal  khat Mengenal  khat
Mengenal khat
 
Auditing unit 1
Auditing unit 1Auditing unit 1
Auditing unit 1
 

Similaire à Javascript: the important bits

Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 

Similaire à Javascript: the important bits (20)

Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Javascript - Beyond-jQuery
Javascript - Beyond-jQueryJavascript - Beyond-jQuery
Javascript - Beyond-jQuery
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5
 
AngularJS Testing Strategies
AngularJS Testing StrategiesAngularJS Testing Strategies
AngularJS Testing Strategies
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 

Dernier

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Dernier (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Javascript: the important bits

  • 1. JAVASCRIPT: THE IMPORTANT BITS REVIEWING JAVASCRIPT AND JQUERY FUNDAMENTALS AS WELL AS A BRIEF INTRO TO NODEJS
  • 2. THINK YOU KNOW JAVASCRIPT? typeof [] === "array"; false 0.1 + 0.2 === 0.3; false a === null; false 0 == '0'; true 1 == '1'; true '' == '0'; false '' == 0; true 'false' == false; false True or false?
  • 3. THINK YOU KNOW JAVASCRIPT? return { a: "hello" } What does this return?
  • 4. THINK YOU KNOW JAVASCRIPT?
  • 5.
  • 6. LET'S GET STARTED WITH THE BASICS.
  • 7. VARIABLES When declairing a variable without the "var", it puts the variable in global space which can be problematic. function hello() { test1 = 'hello'; // global scope var test2 = 'hello2'; // this function scope } hello(); console.log(test1); // 'hello'; console.log(test2); // undefined
  • 8. SCOPING There is no block scoping, only function scoping: for (var i = 0; i < 10; i++) { console.log(i); } console.log(i); // prints 10 If you want to block the scope of the above loop: (function () { for (var i = 0; i < 10; i++) { console.log(i); } }()); var i; console.log(i); // undefined
  • 9. SCOPE IN CALLBACKS In callbacks, you can share variables from the parent function: var obj = { objValue: 'hello', test: function() { var self = this; setTimeout(function() { console.log(this.objValue); // undefined console.log(self.objValue); // 'hello' }, 10); } }
  • 10. OBJECTS AND "CLASSES" Objects are like JSON with some class aspects known as prototypes.
  • 11. OBJECTS AND "CLASSES" An example class: Animal = (function() { function Animal(name) { this.name = name; } Animal.prototype.move = function() { return alert(this.name + ' moved.'); }; return Animal; }());
  • 13. IMMEDIATE EXECUTION FUNCTION (function() { // Your logic here }()); This immediately executes your logic as anonymous scope.
  • 14. PRIVATE PATTERN var getCount = function() { var count = 0; return function() { return ++count; } } var next = getCount(); console.log(next()); // 1 console.log(next()); // 2 This pattern allows you to expose only what you want exposed.
  • 15. INITIALIZATION Variable initialization: var value = value || 'somevalue'; Complex object initialization: ({ val1: 1, val2: null, init: function() { this.val2 = 2; return this; } }).init();
  • 16. LET'S GO OVER JQUERY OPTIMIZATION.
  • 17. SELECTOR CACHING Bad: $('.someclass').text('replace some text.'); $('.someclass').css('color', 'red'); $('.someclass').focus(); Good: $('.someclass') .text('replace some text.') .css('color', 'red') .focus();
  • 18. SELECTOR CACHING Caching with callbacks. var $someotherclass = $('.someotherclass'); $('.someclass').on('click', function(e) { $someotherclass.text('some event'); }); Caching "this": $('.someclass').on('click', function(e)) { $this = $(this); $this.text('something'); $this.hide(); });
  • 19. EVENT ATTACHING When attaching events, use the "on" function. $('a').on('click', function(e)) { console.log('A link was clicked.'); }); What about dynamically generated links? $(document).on('click', 'a', function(e)) { console.log('A link was clicked.'); });
  • 20. PROPERLY STOPPING EVENTS Returning false is not always a good thing: $('a').on('click', function(e) { console.log('Stopping propagation.'); return false; // Same as: // e.preventDefault(); // e.stopPropagation(); }); $('a').on('click', function(e)) { console.log('Another click.'); // Never gets called because of the // return false in the above event. });
  • 21. BASIC JQUERY PLUGIN STRUCTURE (function($) { $.fn.myLog = function() { return this.each(function() { console.log($(this)); }); } }(jQuery)); Usage: $('p').myLog();
  • 23. Nodejs is an event-driven language built on Google's V8 (in c). It's package manager is known as npm and is now packaged with nodejs.
  • 24. NODEJS: HELLO WORLD var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(1337); console.log('Server running on port 1337'); Source: http://nodejs.org/about/
  • 25. NODEJS: DEPENDANCY MANAGEMENT You can manage dependencies for your nodejs app in package.json: { "name": "sample-app", "version": "0.0.1", "dependencies": { "express": "2.5.x" } } This allows us to install our project dependencies with npm: npm install
  • 26. NODEJS: EXPRESS SERVER Our hello world example in express: var express = require('express'); app = express.createServer() app.get('/', function(req, res) { res.send('Hello World'); }); app.listen(1337); console.log('Listening on port 1337');
  • 27. NODEJS: CONNECT MIDDLEWARE Routing middleware is anything that implements the request, response, and next function pattern. // Request logger function logger(req, res, next) { console.log("Path requested: " + req.path); next(); } Using this middleware: app.get('/', logger, function(req, res) { res.send('Hello World'); });