KEMBAR78
Introduction to node.js By Ahmed Assaf | PPTX
Course Overview
 Introduction to Node.js
 Express.js
 MongoDB
 Angular.js
 Cross Platform Mobile Application (Android)
 Introduction to Node.js
 Ahmed Assaf | Senior Software Engineer | ITWorx Education
Module Overview
 About Node
 Setting up your environment
 First Node application
 Node Package Manager (NPM)
Setting Expectations
 Target Audience
 Web Developers
 Web Designers
 Developers with experience using other service side languages such as PHP,
ASP.NET, Python, Ruby etc.
01 | About Node
What is Node?
 Node.js is a runtime environment and library for running JavaScript
applications outside the browser.
 Node.js is mostly used to run real-time server applications and shines through
its performance using non-blocking I/O and asynchronous events.
About Node
 Leverage skills with JavaScript now on the server side
 Unified development environment/language
 High Performance JavaScript Engines – V8
 Open source, created in 2009 by Ryan Dahl
 Windows, Linux, Mac OSX
Node.js' layered architecture
When to use Node
 Node is great for streaming or event-based real-time applications like:
 Chat Applications
 Real time applications and collaborative environments
 Game Servers
 Streaming Servers
 Node is great for when you need high levels of concurrency but little
dedicated CPU time.
 Great for writing JavaScript code everywhere!
Node in the Wild
 Microsoft
 Yahoo!
 LinkedIn
 eBay
 Dow Jones
 Cloud9
 The New York Times, etc
The Node Community
 Five years after its debut, Node is the third most popular project on GitHub.
 Over 2 million downloads per month.
 Over 20 million downloads of v0.10x.
 Over 81,000 modules on npm.
 Over 475 meetups worldwide talking about Node.
 Reference: http://strongloop.com/node-js/infographic/
02 | Setting up your environment
Installing Node on Windows
 http://nodejs.org/ - pre-complied Node.js binaries to install
 https://github.com/joyent/node/wiki/Installation - building it yourself
Path Variable
 Double check that the node executable has been added to your PATH system
environment variable.
 https://www.youtube.com/watch?v=W9pg2FHeoq8 To see how to change your
environment variables on Windows 8 and Windows 8.1.
 You will want to make sure the following folder has been added to the PATH
variable: C:Program Files (x86)nodejs
Installing Node on Ubuntu
 Easiest is to install via the terminal using the package manager.
 You also want to install compilers and build essential tools for packages that
might need them.
sudo apt-get install build-essential
sudo apt-get install nodejs npm
03 | First Node Application
DEMO
Hello World Application
DEMO
Basic HTTP Server
Event Driven Programming
“A programming paradigm in which the flow of the program is determined by
events such as user actions (mouse clicks, key presses) or messages from other
programs.” – Wikipedia
Node Event Loop
 Node provides the event loop as part of the language.
 With Node, there is no call to start the loop.
 The loop starts and doesn’t end until the last callback is complete.
 Event loop is run under a single thread therefore sleep() makes everything
halt.
Blocking I/O
var fs = require('fs');
var contents = fs.readFileSync('package.json')
.toString();
console.log(contents);
Non Blocking I/O
var fs = require('fs');
fs.readFile('package.json', function (err, buf) {
console.log(buf.toString());
});
Callback Style Programming
 Event loops result in callback-style programming
where you break apart a program into its
underlying data flow.
 In other words, you end up splitting your program
into smaller and smaller chunks until each chuck
is mapped to operation with data.
 Why? So that you don’t freeze the event loop on
long-running operations (such as disk or network
I/O).
Callback Insanity
Promises
 A function will return a promise for an object in
the future.
 Promises can be chained together.
 Simplify programming of async systems.
Read More:
http://spin.atomicobject.com/2012/03/14/nodejs-
and-asynchronous-programming-with-promises/
Q Library
step1(function (value1) {
step2(value1, function (value2) {
step3(value2, function (value3) {
step4(value3, function (value4) {
// Do something with value4
});
});
});
});
Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
// Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
})
.done();
DEMO
Basic TCP Demo
Event Emitters
 Allows you to listen for “events” and assign functions to run when events occur.
 Each emitter can emit different types of events.
 The “error” event is special.
 Read More: http://code.tutsplus.com/tutorials/using-nodes-event-module--net-35941
Streams
 Streams represent data streams such as I/O.
 Streams can be piped together.
var fs = require("fs");
// Read File
fs.createReadStream("package.json")
// Write File
.pipe(fs.createWriteStream("out.json"));
Modules and Exports
 Node.js has a simple module and dependencies loading system.
 Unix philosophy -> Node philosophy
 Write programs that do one thing and do it well -> Write modules that do one thing
and do it well.
Require() Module Loading System
 Call the function “require” with the path of the file or directory containing
the module you would like to load.
 Returns a variable containing all the exported functions.
var fs = require("fs");
04 | Node Package Manager (NPM)
What is NPM?
 Official package manager for Node.
 Bundled and installed automatically with the environment.
Frequent Usage:
 npm install --save package_name
 npm update
https://www.npmjs.com/
What is a package.json?
{
"name": “nodetest",
"version": “1.0.0",
"description": “testing npm init",
"main": “index.js",
"author": {
"name": “ahmed assaf",
"email": ""
}
}
http://browsenpm.org/package.json
Popular NPM Modules
Most Depended Upon
 7053 underscore
 6458 async
 5591 request
 4931 lodash
 3630 commander
 3543 express
 2708 optimist
 2634 coffee-script
How does it work?
 Reads package.json
 Installs the dependencies in the local node_modules folder
 In global mode, it makes a node module accessible to all.
 Can install from a folder, web
 Can specify dev or optional dependencies.
Async Module
Async is a utility module which provides straight-forward, powerful functions for working with
asynchronous JavaScript.
async.map(['file1','file2','file3'], fs.stat, function (err, results)
{
// results is now an array of stats for each file
});
async.filter(['file1','file2','file3'], fs.exists, function (results)
{
// results now equals an array of the existing files
});
async.parallel([
function () { },
function () { }
], callback);
async.series([
function () { },
function () { }
]);
Request Module
Request is designed to be the simplest way possible to make http calls. It
supports HTTPS, streaming and follows redirects by default.
var request = require('request');
request('http://www.microsoft.com', function (erro
r, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
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/
 http://browsenpm.org/package.json
 https://www.npmjs.com/
 Github repo: https://github.com/AhmedAssaf/NodeMVA
 From : https://github.com/sayar/NodeMVA
Questions?
Thank You

Introduction to node.js By Ahmed Assaf

  • 1.
    Course Overview  Introductionto Node.js  Express.js  MongoDB  Angular.js  Cross Platform Mobile Application (Android)
  • 2.
     Introduction toNode.js  Ahmed Assaf | Senior Software Engineer | ITWorx Education
  • 3.
    Module Overview  AboutNode  Setting up your environment  First Node application  Node Package Manager (NPM)
  • 4.
    Setting Expectations  TargetAudience  Web Developers  Web Designers  Developers with experience using other service side languages such as PHP, ASP.NET, Python, Ruby etc.
  • 5.
  • 6.
    What is Node? Node.js is a runtime environment and library for running JavaScript applications outside the browser.  Node.js is mostly used to run real-time server applications and shines through its performance using non-blocking I/O and asynchronous events.
  • 7.
    About Node  Leverageskills with JavaScript now on the server side  Unified development environment/language  High Performance JavaScript Engines – V8  Open source, created in 2009 by Ryan Dahl  Windows, Linux, Mac OSX
  • 8.
  • 9.
    When to useNode  Node is great for streaming or event-based real-time applications like:  Chat Applications  Real time applications and collaborative environments  Game Servers  Streaming Servers  Node is great for when you need high levels of concurrency but little dedicated CPU time.  Great for writing JavaScript code everywhere!
  • 10.
    Node in theWild  Microsoft  Yahoo!  LinkedIn  eBay  Dow Jones  Cloud9  The New York Times, etc
  • 11.
    The Node Community Five years after its debut, Node is the third most popular project on GitHub.  Over 2 million downloads per month.  Over 20 million downloads of v0.10x.  Over 81,000 modules on npm.  Over 475 meetups worldwide talking about Node.  Reference: http://strongloop.com/node-js/infographic/
  • 12.
    02 | Settingup your environment
  • 13.
    Installing Node onWindows  http://nodejs.org/ - pre-complied Node.js binaries to install  https://github.com/joyent/node/wiki/Installation - building it yourself
  • 14.
    Path Variable  Doublecheck that the node executable has been added to your PATH system environment variable.  https://www.youtube.com/watch?v=W9pg2FHeoq8 To see how to change your environment variables on Windows 8 and Windows 8.1.  You will want to make sure the following folder has been added to the PATH variable: C:Program Files (x86)nodejs
  • 15.
    Installing Node onUbuntu  Easiest is to install via the terminal using the package manager.  You also want to install compilers and build essential tools for packages that might need them. sudo apt-get install build-essential sudo apt-get install nodejs npm
  • 16.
    03 | FirstNode Application
  • 17.
  • 18.
  • 19.
    Event Driven Programming “Aprogramming paradigm in which the flow of the program is determined by events such as user actions (mouse clicks, key presses) or messages from other programs.” – Wikipedia
  • 20.
    Node Event Loop Node provides the event loop as part of the language.  With Node, there is no call to start the loop.  The loop starts and doesn’t end until the last callback is complete.  Event loop is run under a single thread therefore sleep() makes everything halt.
  • 21.
    Blocking I/O var fs= require('fs'); var contents = fs.readFileSync('package.json') .toString(); console.log(contents);
  • 22.
    Non Blocking I/O varfs = require('fs'); fs.readFile('package.json', function (err, buf) { console.log(buf.toString()); });
  • 23.
    Callback Style Programming Event loops result in callback-style programming where you break apart a program into its underlying data flow.  In other words, you end up splitting your program into smaller and smaller chunks until each chuck is mapped to operation with data.  Why? So that you don’t freeze the event loop on long-running operations (such as disk or network I/O).
  • 24.
  • 25.
    Promises  A functionwill return a promise for an object in the future.  Promises can be chained together.  Simplify programming of async systems. Read More: http://spin.atomicobject.com/2012/03/14/nodejs- and-asynchronous-programming-with-promises/
  • 26.
    Q Library step1(function (value1){ step2(value1, function (value2) { step3(value2, function (value3) { step4(value3, function (value4) { // Do something with value4 }); }); }); }); Q.fcall(promisedStep1) .then(promisedStep2) .then(promisedStep3) .then(promisedStep4) .then(function (value4) { // Do something with value4 }) .catch(function (error) { // Handle any error from all above steps }) .done();
  • 27.
  • 28.
    Event Emitters  Allowsyou to listen for “events” and assign functions to run when events occur.  Each emitter can emit different types of events.  The “error” event is special.  Read More: http://code.tutsplus.com/tutorials/using-nodes-event-module--net-35941
  • 29.
    Streams  Streams representdata streams such as I/O.  Streams can be piped together. var fs = require("fs"); // Read File fs.createReadStream("package.json") // Write File .pipe(fs.createWriteStream("out.json"));
  • 30.
    Modules and Exports Node.js has a simple module and dependencies loading system.  Unix philosophy -> Node philosophy  Write programs that do one thing and do it well -> Write modules that do one thing and do it well.
  • 31.
    Require() Module LoadingSystem  Call the function “require” with the path of the file or directory containing the module you would like to load.  Returns a variable containing all the exported functions. var fs = require("fs");
  • 32.
    04 | NodePackage Manager (NPM)
  • 33.
    What is NPM? Official package manager for Node.  Bundled and installed automatically with the environment. Frequent Usage:  npm install --save package_name  npm update https://www.npmjs.com/
  • 34.
    What is apackage.json? { "name": “nodetest", "version": “1.0.0", "description": “testing npm init", "main": “index.js", "author": { "name": “ahmed assaf", "email": "" } } http://browsenpm.org/package.json
  • 35.
    Popular NPM Modules MostDepended Upon  7053 underscore  6458 async  5591 request  4931 lodash  3630 commander  3543 express  2708 optimist  2634 coffee-script
  • 36.
    How does itwork?  Reads package.json  Installs the dependencies in the local node_modules folder  In global mode, it makes a node module accessible to all.  Can install from a folder, web  Can specify dev or optional dependencies.
  • 37.
    Async Module Async isa utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. async.map(['file1','file2','file3'], fs.stat, function (err, results) { // results is now an array of stats for each file }); async.filter(['file1','file2','file3'], fs.exists, function (results) { // results now equals an array of the existing files }); async.parallel([ function () { }, function () { } ], callback); async.series([ function () { }, function () { } ]);
  • 38.
    Request Module Request isdesigned to be the simplest way possible to make http calls. It supports HTTPS, streaming and follows redirects by default. var request = require('request'); request('http://www.microsoft.com', function (erro r, response, body) { if (!error && response.statusCode == 200) { console.log(body); } });
  • 39.
    Resources  Using Node.jswith 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/  http://browsenpm.org/package.json  https://www.npmjs.com/  Github repo: https://github.com/AhmedAssaf/NodeMVA  From : https://github.com/sayar/NodeMVA
  • 40.
  • 41.

Editor's Notes

  • #3 2
  • #6 5
  • #9 Node.js currently builds on top of several key dependencies including the V8 JavaScript engine, libuv, openssl and others. The Node.js Application Binary Interface provides access to functionality central to how Node.js operates. The Node.js Core Library is the primary interface through which most Modules and Applications built on top of Node perform I/O operations, manipulate data, access the network, etc. Some modules and applications choose to go beyond the Core Library and bind directly to the Application Binary Interface and dependencies to perform more advanced operations. An optional Binary abstraction layer is used to buffer module and application developers from changes in the Application Binary Interface and Dependencies. Due to the existing layering, modules and applications are sensitive not only to changes in the Core Library API, but the Application Binary Interface and dependendencies as well.
  • #13 12
  • #17 16
  • #19 Hello World in Node.js As is typical in other languages, the generated code example shows you how to output “Hello World” in the browser. Let me explain how the generated code in server.js works line by line. *Note: As stated in this tutorial series description, I am assuming you have a knowledge of JavaScript, HTML5 and how HTTP/the Internet work. Line 1 var http = require('http'); Node.js has a simple module and dependencies loading system. You simply call the function “require” with the path of the file or directory containing the module you would like to load at which point a variable is returned containing all the exported functions of that module. Line 2 var port = process.env.port || 1337; On this line, we want to determine on which port the HTTP server serving the HTML should run. If a port number is specified in the environment variables, we will use that one or we will simply use 1337. Line 3 http.createServer(function (req, res) { We want to create a server to handle HTTP requests. We will also pass the createServer function a function callback containing two parameters to a handle each individual request and return a response. Take a look at Michael Vollmer’s article if you’ve never encountered callback functions in JavaScript. The request received is passed in the req parameter and the response is expected to written to the res parameter. Line 4 res.writeHead(200, { 'Content-Type': 'text/plain' }); Any HTTP response requires a status-line and headers, to learn more about HTTP headers and how they work check out this article. In this case, we want to return 200 OK as the status response and to specify the content-type as plain text. We specify this by calling the writeHead function on the response object. Line 5 res.end('Hello World\n'); Once we are done writing the response we want to call the end function. We can also pass the final content through the end function, in this case we want to send the string “Hello World” in plain text. Line 6 }).listen(port); We close off the callback and call the function listen at the port we defined earlier, this will start the server and start accepting requests sent to the defined port. To see the result, you can start debugging by pressing on the button shown in the previous screenshot. You can see “Hello World” in the browser.
  • #31 How do I define the interface for my module? module.exports used to define your interface module is defined via closure during the compile process module.exports is what is assigned as a result of the require() call
  • #32 How do I use a module? Import it via require require brings the interface of the module into scope and assigns it to path How does require find a module? Searches: Core Modules Built in modules node_modules Works up path until it matches or hits the root NODE_PATH Includes globally installed packages $HOME/.node_modules -- Are not recommended $HOME/.node_libraries -- Are not recommended How can I load a local module? / for absolute path ./ for relative path Why don’t I specify myFirstModule.js? var myFirstModule = require('./myFirstModule'); This could refer to: myFirstModule as a file myFirstModule.js as a file myFirstModule is a directory it will attempt to load myFirstModule/index.js How does require really work? Abstraction around module.require which wraps Module._load() _load steps: Check Module._cache for a cached copy Create a new Module instance if cache miss Save it to the cache Call load with the given filename Compile the file contents If there was an error delete from cache Return module.exports How does compile work? Create a standalone require function that calls module.require Attaches other helper methods to require Wraps the loaded JS code in a function that provides the require from step 1, module, and variables to the module scope Runs the function (function (exports, require, module, __filename, __dirname) { // Code injected here });
  • #33 32
  • #35 Major version minor version ^14.4.1 ~1.3.4