我爱编程

2 Node.js Introduction

2015-10-29  本文已影响20人  闷油瓶小张

Familiarity with JavaScript


The Problem with I/O


An Example Web Server

The life cycle:

  1. A request comes in to the web server. The client has requested every car in out database that is "red."
  2. 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.
  3. The database engine runs the query and assembles the results.
  4. The database server reponds to our web server with the results.
  5. The web server receives the query results and turns them into JSON so that the results are easier to process.
  6. The server reads from the local file system to find an appropriate HTML document to display the results.
  7. 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.

上一篇 下一篇

猜你喜欢

热点阅读