– node.js – Things you need to know



– node.js – Things you need to know

0 0


node-in-5

An extremely brief introduction to node.js

On Github RobPhippen / node-in-5

node.js

a beginner's guide
Rob Phippen

what the heck is node?

A tiny (5.6MB install) runtime for creating web Servers using JavaScript that is generating a lot of interest

Part of the 'JavaScript everywhere' thing

See Jerry Cuomo talking about it here

show me some code

The 'Hello World' server

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/'); 

...run that by me again...

Load the http module

var http = require('http');

...create a server

http.createServer(...
)...

...passing a callback - which we declare inline  

http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n');})...

...and finally setting our server to listen on port 1337

 <span>http.createServer(function (req, res) {</span>  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

Neat things about node

#1 npm
  • Node Package Manager
  • 41000 Packages
install a package like this
c:\users\phippen> npm install node-red
...which is an advertisement for our very own @knolleary's Node Red, a visual programming environment for node

Things you need to know

#1 node is single threaded

!

...it's better than it sounds

Your code runs in a single thread

All IO operations happen asynchronously

When you call an IO operation, you're adding an event to an event queueNode runs an 'event loop' that picks up an event processes it when it's done, calls your callback

...and you can create 'clusters' of nodes

    var cluster = require('cluster');

    if (cluster.isMaster) {
        //start up workers for each cpu
        require('os').cpus().forEach(function() {
            cluster.fork();
        });

    } else {
        //load up your application as a worker
        require('./app.js');
    }

Find this presentation at

http://slid.es/robphippen/node-in-5

Enhance and beautify it here

https://github.com/RobPhippen/node-in-5