Familiarity with JavaScript
The Problem with I/O
An Example Web Server
The life cycle:
- A request comes in to the web server. The client has requested every car in out database that is "red."
- A second remote server houses our corporate database. Our web server creates a database query and sends it off to the remote server housing our database.
- The database engine runs the query and assembles the results.
- The database server reponds to our web server with the results.
- The web server receives the query results and turns them into JSON so that the results are easier to process.
- The server reads from the local file system to find an appropriate HTML document to display the results.
- The server responds to the request and returns HTML with all the red cars in our database.
Stepping Around the I/O Problem
Example Web Server Revisited
Real World Data
Your First Node.js Server
Installing Node.js
Writing the 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/');
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url === '/favicon.ico') {
return res.end();
}
console.log('Incoming request to ' + req.url);
var i = 2;
res.writeHead(200, {'Content-Type': 'text/plain'});
setTimeout(function() {
fs.readFile(__filename, {
encoding: 'utf8'
}, function (error, contents) {
if (error) {
console.error(error);
return res.end();
}
console.log('sending response for ' + req.url);
res.end(contents);
});
}, 5000);
while(i--) {
console.log('Loop value: ' + i + '\r');
}
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Our Server in Action
Summary
Node.js provides non-blocking asynchronous I/O.