SlideShare uma empresa Scribd logo
1 de 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?

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

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

Semelhante a Get $300 in free cloud services for 6 months

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
 

Semelhante a Get $300 in free cloud services for 6 months (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
 

Último

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Último (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Get $300 in free cloud services for 6 months

  • 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--; };