SlideShare une entreprise Scribd logo
1  sur  15
A Special Thank You To Our Sponsor

Rackspace is dedicated to making all developers' lives easier and we're passionate about supporting
collaborative open source projects and communities.
When you sign up today, you will get $300 in free cloud services - that's up to $50 per month credit
for six months on your Rackspace Cloud account, powered by OpenStack™

http://developer.rackspace.com/devtrial/
Intro to Node.js
A hands on journey to awesomeness!
Getting Started
Mac OS X – Download the image from http://nodejs.org double click
the disk images and run the installer
Windows – Download the installer from http://nodejs.org and run the
installer.
Ubuntu Linux – Add Chris Lea’s PPA ppa:chris-lea/node.js
sudo add-apt-repository ppa:chris-lea/node.js
apt-get update
apt-get install nodejs
Grab the Exercise Files
Clone the repository with GIT
git clone https://github.com/ccowan/intro-to-node.git

Or download
https://github.com/ccowan/intro-to-node/archive/master.zip
Exercise 1: Hello Mars!
Node.js is a V8 interpreter, so if you’ve ever used console.log in Firebug or Chorme Dev tools it
works the same way.
Step 1: Create a file called hello-mars.js with the following:

console.log("Hello Mars");
Step 2: Open a console run the following (Mac OS X - Terminal, Windows – CMD, Linux - Term):

node hello-mars.js
Extra Credit: Arguments are passed to the script via the process.args array. Create an app that will
repeat a messing with the arguments passed to it.

node hello-mars.js “Houston Calling”
Exercise 2: I/O Fun!
A simple example of I/O is reading a file from the file system. To do this we need to
use the file system module. Loading modules in Node.js is done using the
require() method. To load the file system module you would do the following:
var fs = require('fs');

In this example require(‘fs’) will return the file system module which is an object with
methods for working with the file system.
One of the methods is fs.readFileSync() which will read a from the file system. It takes two
arguments: filename, options. The readFileSync will return a Buffer by default unless you set the
option’s encoding attribute to ‘utf8’, then it will return a string.

Assignment: Create a script that will read the contents of
./data/exercise-02.txt and output it to the console.
Exercise 2: Solution
var fs = require('fs');
var contents = fs.readFileSync('./data/exercise-02.txt', { encoding: 'utf8' });
cosnole.log(contents);

Should output the following:
Houston, we have a problem! I say again… Houston we have a problem!
Exercise 3: Async I/O
On of Node.js biggest advantage is that it’s an asynchronous language. So when you have the option
ALWAYS use the asynchronous method. In previous example we used the fs.readFileSync() method.
But there’s a better way… fs.readFile()
fs.readFile() takes three arguments: filename, options, and callback function. When the read file
operation is finished, the callback function is called. The callback function will be passed two
arguments: err and data. It looks something like this:
var fs = require('fs');
var options = { encoding: 'utf8' };
fs.readFile('./data/exercise-03.txt', options, function (err, data) {
// Do something here...
});

Assignment: Read ./data/exercise-03-1.txt, ./data/exercise-03-2.txt,
and ./data/exercise-03-3.txt (in that order) and output a message to
the console when they are complete. Hint: Do NOT output the contents!
Exercise 3: Solution
var fs = require('fs');
var options = { encoding: 'utf8' };

fs.readFile('./data/exercise-03-1.txt', options, function (err, data) {

console.log('./data/exercise-03-1.txt loaded');
});

fs.readFile('./data/exercise-03-2.txt', options, function (err, data) {
console.log('./data/exercise-03-2.txt loaded');
});

fs.readFile('./data/exercise-03-3.txt', options, function (err, data) {
console.log('./data/exercise-03-3.txt loaded');
});
Exercise 4: HTTP Server
On of the many uses for Node.js is building an HTTP server. Sometimes you only need a very simple
server, the Core HTTP Server is perfect for that.

To create an HTTP Server you need to require() the ‘http’ module then use the http.createServer()
function to create an instance. The createServer() function takes a callback. The callback is called
for every request to the server and it’s passed two arguments: a request object and a response
object. Here’s a simple example:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Assignment: Create a simple HTTP server that will serve
./data/exercise-03-2 for each request.
Exercise 4: Solution
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {

var options = { encoding: 'utf8' };
fs.readFile('../data/exercise-03-2.txt', options, function (err, data) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(data);

});
}).listen(1337, '127.0.0.1');
Exercise 5: Modules
The killer feature of Node.js is the module eco-system. You can install modules using the
Node Package Manager, NPM. Here is how you would install the Express framework
npm install express

NPM modules are installed into the node_modules directory in the current folder. When you call
require(‘express’) it looks in the current folder then starts to walk up the tree till it finds a node_modules
directory.
You can also create your own modules by using the CommonJS module format. Module files can be store
anywhere within your project, but you have to give a relative or full path. Here is an example of a module
being loaded from the current directory:
var multiply = require('./multiply');

In the example above the require function will first look in the current directory for a file named multiply.js. If
it doesn’t find that file then it will try to look in multiply/index.js.
Exercise 5: Modules
Creating a module is as easy as assigning the module.exports variable in a
JavaScript file. The variable can be a function, object, string, number or variable.
module.exports = function (a, b) { return a * b; };

Modules are also cached so when the file is loaded it’s contents are cached in
memory. The next time the file is included if they cache exists then it’s returned
instead of loading a new file. This allows us to some interesting things.
Assignment: Create a counter module that has increment and decrement
functions. When the functions are executed the current count should be returned.
Exercise 5: Solution
var count = 0;
module.exports.increment = function () {
return count++;
};
module.exports.decrement = function () {
return count--;
};
Questions?

Contenu connexe

Tendances

MySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKMySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKI Goo Lee
 
pam_container -- jeszcze lżejsza wirtualizacja
pam_container -- jeszcze lżejsza wirtualizacjapam_container -- jeszcze lżejsza wirtualizacja
pam_container -- jeszcze lżejsza wirtualizacjagnosek
 
Puppet Camp Phoenix 2015: Managing Files via Puppet: Let Me Count The Ways (B...
Puppet Camp Phoenix 2015: Managing Files via Puppet: Let Me Count The Ways (B...Puppet Camp Phoenix 2015: Managing Files via Puppet: Let Me Count The Ways (B...
Puppet Camp Phoenix 2015: Managing Files via Puppet: Let Me Count The Ways (B...Puppet
 
Advanced Replication
Advanced ReplicationAdvanced Replication
Advanced ReplicationMongoDB
 
CloudOps CloudStack Days, Austin April 2015
CloudOps CloudStack Days, Austin April 2015CloudOps CloudStack Days, Austin April 2015
CloudOps CloudStack Days, Austin April 2015CloudOps2005
 
Cloud init and cloud provisioning [openstack summit vancouver]
Cloud init and cloud provisioning [openstack summit vancouver]Cloud init and cloud provisioning [openstack summit vancouver]
Cloud init and cloud provisioning [openstack summit vancouver]Joshua Harlow
 
Getting Started with Couchbase Ruby
Getting Started with Couchbase RubyGetting Started with Couchbase Ruby
Getting Started with Couchbase RubySergey Avseyev
 
Python mongo db-training-europython-2011
Python mongo db-training-europython-2011Python mongo db-training-europython-2011
Python mongo db-training-europython-2011Andreas Jung
 
Python And My Sq Ldb Module
Python And My Sq Ldb ModulePython And My Sq Ldb Module
Python And My Sq Ldb ModuleAkramWaseem
 
Deploying Symfony2 app with Ansible
Deploying Symfony2 app with AnsibleDeploying Symfony2 app with Ansible
Deploying Symfony2 app with AnsibleRoman Rodomansky
 
How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)Felix Geisendörfer
 
Install and Configure Ubuntu for Hadoop Installation for beginners
Install and Configure Ubuntu for Hadoop Installation for beginners Install and Configure Ubuntu for Hadoop Installation for beginners
Install and Configure Ubuntu for Hadoop Installation for beginners Shilpa Hemaraj
 

Tendances (20)

Mysql all
Mysql allMysql all
Mysql all
 
MySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKMySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELK
 
Inheritance
InheritanceInheritance
Inheritance
 
Configuration Management in Ansible
Configuration Management in Ansible Configuration Management in Ansible
Configuration Management in Ansible
 
pam_container -- jeszcze lżejsza wirtualizacja
pam_container -- jeszcze lżejsza wirtualizacjapam_container -- jeszcze lżejsza wirtualizacja
pam_container -- jeszcze lżejsza wirtualizacja
 
GoDocker presentation
GoDocker presentationGoDocker presentation
GoDocker presentation
 
Node.js in production
Node.js in productionNode.js in production
Node.js in production
 
CloudInit Introduction
CloudInit IntroductionCloudInit Introduction
CloudInit Introduction
 
Puppet Camp Phoenix 2015: Managing Files via Puppet: Let Me Count The Ways (B...
Puppet Camp Phoenix 2015: Managing Files via Puppet: Let Me Count The Ways (B...Puppet Camp Phoenix 2015: Managing Files via Puppet: Let Me Count The Ways (B...
Puppet Camp Phoenix 2015: Managing Files via Puppet: Let Me Count The Ways (B...
 
Cloudinit
CloudinitCloudinit
Cloudinit
 
Advanced Replication
Advanced ReplicationAdvanced Replication
Advanced Replication
 
CloudOps CloudStack Days, Austin April 2015
CloudOps CloudStack Days, Austin April 2015CloudOps CloudStack Days, Austin April 2015
CloudOps CloudStack Days, Austin April 2015
 
Cloud init and cloud provisioning [openstack summit vancouver]
Cloud init and cloud provisioning [openstack summit vancouver]Cloud init and cloud provisioning [openstack summit vancouver]
Cloud init and cloud provisioning [openstack summit vancouver]
 
Event loop
Event loopEvent loop
Event loop
 
Getting Started with Couchbase Ruby
Getting Started with Couchbase RubyGetting Started with Couchbase Ruby
Getting Started with Couchbase Ruby
 
Python mongo db-training-europython-2011
Python mongo db-training-europython-2011Python mongo db-training-europython-2011
Python mongo db-training-europython-2011
 
Python And My Sq Ldb Module
Python And My Sq Ldb ModulePython And My Sq Ldb Module
Python And My Sq Ldb Module
 
Deploying Symfony2 app with Ansible
Deploying Symfony2 app with AnsibleDeploying Symfony2 app with Ansible
Deploying Symfony2 app with Ansible
 
How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)
 
Install and Configure Ubuntu for Hadoop Installation for beginners
Install and Configure Ubuntu for Hadoop Installation for beginners Install and Configure Ubuntu for Hadoop Installation for beginners
Install and Configure Ubuntu for Hadoop Installation for beginners
 

En vedette

Knockout vs. angular
Knockout vs. angularKnockout vs. angular
Knockout vs. angularMaslowB
 
Sfd2012Hanoi Nguyễn Hà Dương - Introduction to Node.js
Sfd2012Hanoi Nguyễn Hà Dương - Introduction to Node.jsSfd2012Hanoi Nguyễn Hà Dương - Introduction to Node.js
Sfd2012Hanoi Nguyễn Hà Dương - Introduction to Node.jsVu Hung Nguyen
 
JS Frameworks - Angular Vs Backbone
JS Frameworks - Angular Vs BackboneJS Frameworks - Angular Vs Backbone
JS Frameworks - Angular Vs BackboneGourav Jain, MCTS®
 
wwc start-launched
wwc start-launchedwwc start-launched
wwc start-launchedMat Schaffer
 
PTW Rails Bootcamp
PTW Rails BootcampPTW Rails Bootcamp
PTW Rails BootcampMat Schaffer
 

En vedette (8)

Knockout vs. angular
Knockout vs. angularKnockout vs. angular
Knockout vs. angular
 
Sfd2012Hanoi Nguyễn Hà Dương - Introduction to Node.js
Sfd2012Hanoi Nguyễn Hà Dương - Introduction to Node.jsSfd2012Hanoi Nguyễn Hà Dương - Introduction to Node.js
Sfd2012Hanoi Nguyễn Hà Dương - Introduction to Node.js
 
JS Frameworks - Angular Vs Backbone
JS Frameworks - Angular Vs BackboneJS Frameworks - Angular Vs Backbone
JS Frameworks - Angular Vs Backbone
 
wwc start-launched
wwc start-launchedwwc start-launched
wwc start-launched
 
Node.js
Node.jsNode.js
Node.js
 
Ruby on the Phone
Ruby on the PhoneRuby on the Phone
Ruby on the Phone
 
PTW Rails Bootcamp
PTW Rails BootcampPTW Rails Bootcamp
PTW Rails Bootcamp
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 

Similaire à Hands On Intro to Node.js

File System in Nodejs.pdf
File System in Nodejs.pdfFile System in Nodejs.pdf
File System in Nodejs.pdfSudhanshiBakre1
 
SCasia 2018 MSFT hands on session for Azure Batch AI
SCasia 2018 MSFT hands on session for Azure Batch AISCasia 2018 MSFT hands on session for Azure Batch AI
SCasia 2018 MSFT hands on session for Azure Batch AIHiroshi Tanaka
 
Exploit Frameworks
Exploit FrameworksExploit Frameworks
Exploit Frameworksphanleson
 
Best Practices For Direct Admin Security
Best Practices For Direct Admin SecurityBest Practices For Direct Admin Security
Best Practices For Direct Admin Securitylisa Dsouza
 
Serving Moodle Presentation
Serving Moodle PresentationServing Moodle Presentation
Serving Moodle Presentationwebhostingguy
 
Node.js basics
Node.js basicsNode.js basics
Node.js basicsBen Lin
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdfSudhanshiBakre1
 
Bc0056 unix operating system
Bc0056   unix operating systemBc0056   unix operating system
Bc0056 unix operating systemsmumbahelp
 
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docxtarifarmarie
 
NodeJs
NodeJsNodeJs
NodeJsdizabl
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core ModuleKatie Gulley
 

Similaire à Hands On Intro to Node.js (20)

Requiring your own files.pptx
Requiring your own files.pptxRequiring your own files.pptx
Requiring your own files.pptx
 
Lab 1 Essay
Lab 1 EssayLab 1 Essay
Lab 1 Essay
 
File System in Nodejs.pdf
File System in Nodejs.pdfFile System in Nodejs.pdf
File System in Nodejs.pdf
 
SCasia 2018 MSFT hands on session for Azure Batch AI
SCasia 2018 MSFT hands on session for Azure Batch AISCasia 2018 MSFT hands on session for Azure Batch AI
SCasia 2018 MSFT hands on session for Azure Batch AI
 
Exploit Frameworks
Exploit FrameworksExploit Frameworks
Exploit Frameworks
 
Drupal Modules
Drupal ModulesDrupal Modules
Drupal Modules
 
Tutorial on Node File System
Tutorial on Node File SystemTutorial on Node File System
Tutorial on Node File System
 
Best Practices For Direct Admin Security
Best Practices For Direct Admin SecurityBest Practices For Direct Admin Security
Best Practices For Direct Admin Security
 
backend
backendbackend
backend
 
backend
backendbackend
backend
 
Serving Moodle Presentation
Serving Moodle PresentationServing Moodle Presentation
Serving Moodle Presentation
 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
 
Bc0056 unix operating system
Bc0056   unix operating systemBc0056   unix operating system
Bc0056 unix operating system
 
NodeJs Session02
NodeJs Session02NodeJs Session02
NodeJs Session02
 
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx
 
NodeJs
NodeJsNodeJs
NodeJs
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
 
NodeJs Modules1.pdf
NodeJs Modules1.pdfNodeJs Modules1.pdf
NodeJs Modules1.pdf
 

Dernier

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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 TerraformAndrey Devyatkin
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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, Adobeapidays
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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 WorkerThousandEyes
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 

Dernier (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech 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
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Hands On Intro to Node.js

  • 1. A Special Thank You To Our Sponsor Rackspace is dedicated to making all developers' lives easier and we're passionate about supporting collaborative open source projects and communities. When you sign up today, you will get $300 in free cloud services - that's up to $50 per month credit for six months on your Rackspace Cloud account, powered by OpenStack™ http://developer.rackspace.com/devtrial/
  • 2. Intro to Node.js A hands on journey to awesomeness!
  • 3. Getting Started Mac OS X – Download the image from http://nodejs.org double click the disk images and run the installer Windows – Download the installer from http://nodejs.org and run the installer. Ubuntu Linux – Add Chris Lea’s PPA ppa:chris-lea/node.js sudo add-apt-repository ppa:chris-lea/node.js apt-get update apt-get install nodejs
  • 4. Grab the Exercise Files Clone the repository with GIT git clone https://github.com/ccowan/intro-to-node.git Or download https://github.com/ccowan/intro-to-node/archive/master.zip
  • 5. Exercise 1: Hello Mars! Node.js is a V8 interpreter, so if you’ve ever used console.log in Firebug or Chorme Dev tools it works the same way. Step 1: Create a file called hello-mars.js with the following: console.log("Hello Mars"); Step 2: Open a console run the following (Mac OS X - Terminal, Windows – CMD, Linux - Term): node hello-mars.js Extra Credit: Arguments are passed to the script via the process.args array. Create an app that will repeat a messing with the arguments passed to it. node hello-mars.js “Houston Calling”
  • 6. Exercise 2: I/O Fun! A simple example of I/O is reading a file from the file system. To do this we need to use the file system module. Loading modules in Node.js is done using the require() method. To load the file system module you would do the following: var fs = require('fs'); In this example require(‘fs’) will return the file system module which is an object with methods for working with the file system. One of the methods is fs.readFileSync() which will read a from the file system. It takes two arguments: filename, options. The readFileSync will return a Buffer by default unless you set the option’s encoding attribute to ‘utf8’, then it will return a string. Assignment: Create a script that will read the contents of ./data/exercise-02.txt and output it to the console.
  • 7. Exercise 2: Solution var fs = require('fs'); var contents = fs.readFileSync('./data/exercise-02.txt', { encoding: 'utf8' }); cosnole.log(contents); Should output the following: Houston, we have a problem! I say again… Houston we have a problem!
  • 8. Exercise 3: Async I/O On of Node.js biggest advantage is that it’s an asynchronous language. So when you have the option ALWAYS use the asynchronous method. In previous example we used the fs.readFileSync() method. But there’s a better way… fs.readFile() fs.readFile() takes three arguments: filename, options, and callback function. When the read file operation is finished, the callback function is called. The callback function will be passed two arguments: err and data. It looks something like this: var fs = require('fs'); var options = { encoding: 'utf8' }; fs.readFile('./data/exercise-03.txt', options, function (err, data) { // Do something here... }); Assignment: Read ./data/exercise-03-1.txt, ./data/exercise-03-2.txt, and ./data/exercise-03-3.txt (in that order) and output a message to the console when they are complete. Hint: Do NOT output the contents!
  • 9. Exercise 3: Solution var fs = require('fs'); var options = { encoding: 'utf8' }; fs.readFile('./data/exercise-03-1.txt', options, function (err, data) { console.log('./data/exercise-03-1.txt loaded'); }); fs.readFile('./data/exercise-03-2.txt', options, function (err, data) { console.log('./data/exercise-03-2.txt loaded'); }); fs.readFile('./data/exercise-03-3.txt', options, function (err, data) { console.log('./data/exercise-03-3.txt loaded'); });
  • 10. Exercise 4: HTTP Server On of the many uses for Node.js is building an HTTP server. Sometimes you only need a very simple server, the Core HTTP Server is perfect for that. To create an HTTP Server you need to require() the ‘http’ module then use the http.createServer() function to create an instance. The createServer() function takes a callback. The callback is called for every request to the server and it’s passed two arguments: a request object and a response object. Here’s a simple example: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); Assignment: Create a simple HTTP server that will serve ./data/exercise-03-2 for each request.
  • 11. Exercise 4: Solution var http = require('http'); var fs = require('fs'); http.createServer(function (req, res) { var options = { encoding: 'utf8' }; fs.readFile('../data/exercise-03-2.txt', options, function (err, data) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(data); }); }).listen(1337, '127.0.0.1');
  • 12. Exercise 5: Modules The killer feature of Node.js is the module eco-system. You can install modules using the Node Package Manager, NPM. Here is how you would install the Express framework npm install express NPM modules are installed into the node_modules directory in the current folder. When you call require(‘express’) it looks in the current folder then starts to walk up the tree till it finds a node_modules directory. You can also create your own modules by using the CommonJS module format. Module files can be store anywhere within your project, but you have to give a relative or full path. Here is an example of a module being loaded from the current directory: var multiply = require('./multiply'); In the example above the require function will first look in the current directory for a file named multiply.js. If it doesn’t find that file then it will try to look in multiply/index.js.
  • 13. Exercise 5: Modules Creating a module is as easy as assigning the module.exports variable in a JavaScript file. The variable can be a function, object, string, number or variable. module.exports = function (a, b) { return a * b; }; Modules are also cached so when the file is loaded it’s contents are cached in memory. The next time the file is included if they cache exists then it’s returned instead of loading a new file. This allows us to some interesting things. Assignment: Create a counter module that has increment and decrement functions. When the functions are executed the current count should be returned.
  • 14. Exercise 5: Solution var count = 0; module.exports.increment = function () { return count++; }; module.exports.decrement = function () { return count--; };