2 Node.js Introduction

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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容