• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Hands On Intro to Node.js
 

Hands On Intro to Node.js

on

  • 919 views

A hands on journey to awesomeness. Learn the very basics of using Node.js with 5 basic exercises to get you started.

A hands on journey to awesomeness. Learn the very basics of using Node.js with 5 basic exercises to get you started.

Statistics

Views

Total Views
919
Views on SlideShare
918
Embed Views
1

Actions

Likes
1
Downloads
2
Comments
0

1 Embed 1

https://twitter.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Hands On Intro to Node.js Hands On Intro to Node.js Presentation Transcript

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