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