follow along at
Servers have to handle lots of requests.
What happens when the server has to do something like this?
var result = database.query("kittens");
// finger twaddling
send(result);
The database query is blocking the thread from continuing!
Nodejs uses callbacks to defer dealing with I/O until it's ready
database.query("kittens", function (data) {
// database is done and has the data ready
send(data);
});
// do other servery things
skynet.spawn({"model": "T-1000"});
we'll explore callbacks and javascript language features later
Simple http server
var http = require('http');
function requestHandler(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello CSE 333\n');
}
http.createServer(requestHandler).listen(1337, '127.0.0.1');
Uber, Yahoo, Microsoft, Ebay, Cloud9 IDE, Dow Jones, LinkedIn, The New York Times, PayPal, Mal-Wart
Calculate first 25,000 primes
primes.cc, primes.js, timeprimes.sh
c++:
287107
real 0m1.593s
user 0m1.589s
sys 0m0.002s
v8:
287107
real 0m3.676s
user 0m3.662s
sys 0m0.012s
Hello world in C, v8, java and node
Remember that v8 and node are both compiling js!
Nodejs has a few components written in C for performance
freaking awesome logo btw
// Grab every div on the page
var divs = document.querySelectorAll("div");
// Loop through each element
for (var i = 0; i < divs.length; i++) {
// Change the background image
divs[i].style.backgroundImage = "url('http://nodejs-slides.stfn.me/files/kitten.jpg')";
}
But now it does so much more!
Callbacks are functions that are passed as parameters to other functions, and then called within those functions
function helloCaller(helloFn, name) {
helloFn(name);
}
function hello(name) { console.log("hello " + name); }
function swedishHello(name) { console.log("hej " + name); }
helloCaller(hello, "CSE 333");
helloCaller(swedishHello, "CSE 333");
var http = require('http');
function requestHandler(request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('<h1>MLP Fan Site</h1>');
}
http.createServer(requestHandler).listen(1337, '127.0.0.1');
requestHandler
as the callbackWrite the contents of a file to a socket
var net = require('net');
var fs = require('fs');
var host = process.argv[2];
var port = process.argv[3];
var filename = process.argv[4];
var socket = new net.Socket();
socket.connect(port, host, function() {
fs.readFile(filename, function (error, data) {
socket.write(data);
process.exit();
});
});
node ex15.js stfn.me 5000 filename
You can do bad things
var http = require('http');
var sys = require('sys');
var spawn = require('child_process').spawn;
http.createServer(function (req, res) {
var ls = spawn('ls', ['-lh', '/']);
ls.stdout.on('data', function(data) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(data.toString('ascii'));
})
}).listen(3555, '127.0.0.1');
...and many more!
Nodejs...
To connect, open terminal and type
nc stfn.me 5000