nodejs mvc

原文地址:http://www.cnblogs.com/QLeelulu/archive/2011/01/28/nodejs_into_and_n2mvc.html

Node.js:用JavaScript写服务器端程序-介绍并写个MVC框架

(注:1、本文基于Node.js V0.3.6; 2、本文假设你了解JavaScript; 3、本文假设你了解MVC框架;4、本文作者:QLeelulu,转载请注明出处。5、本文示例源代码learnNode.zip)

Node.js是什么

Node让你可以用javascript编写服务器端程序,让javascript脱离web浏览器的限制,像C#、JAVA、Python等语言一样在服务器端运行,这也让一些熟悉Javascript的前端开发人员进军到服务器端开发提供了一个便利的途径。 Node是基于Google的V8引擎封装的,并提供了一些编写服务器程序的常用接口,例如文件流的处理。Node的目的是提供一种简单的途径来编写高性能的网络程序。

Node.js的性能

hello world 测试:

clip_image002

300并发请求,返回不同大小的内容:

clip_image004

为什么node有如此高的性能?看node的特性。

Node.js的特性

1. 单线程

2. 非阻塞IO

3. Google V8

4. 事件驱动

更详细的了解node请看淘宝UED博客上的关于node.js的一个幻灯片:http://www.slideshare.net/lijing00333/node-js

你好,世界

这,当然是俗套的Hello World啦(hello_world.js):

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

require类似于C#的using、Python的import,用于导入模块(module)。node使用的是CommonJS的模块系统。http.createServer 的参数为一个函数,每当有新的请求进来的时候,就会触发这个函数。最后就是绑定要监听的端口。

怎么运行?

当然,是先安装node.js啦。到http://nodejs.org/下载并编译,支持Linux、Mac,也支持windows下的Cygwin。具体的安装说明见:http://howtonode.org/how-to-install-nodejs

装好node后,就可以运行我们的hello world了:

$ node hello_world.js
Server running at http:
//127.0.0.1:8124/

clip_image006

编程习惯的改变?

我们来写一个读取文件内容的脚本:

 

01 //output_me.js
02 var fs = require('fs'), fileContent = 'nothing';
03 fs.readFile(__filename, "utf-8"function(err, file) { 
04     if(err) { 
05         console.log(err);
06         return
07     }
08     fileContent = file;
09     console.log('end readfile \n');
10 });
11 console.log('doSomethingWithFile: '+ fileContent +'\n');

这个脚本读取当前文件的内容并输出。__filename是node的一个全局变量,值为当前文件的绝对路径。我们执行这个脚本看一下:

clip_image008

有没发现结果不对呢?打印的fileContent并不是读取到的文件内容,而是初始化的时候赋值的nothing,并且‘end readfile’最后才打印出来。前面我们提到node的一个特性就是非阻塞IO,而readFile就是异步非阻塞读取文件内容的,所以后面的代码并不会等到文件内容读取完了再执行。请谨记node的异步非阻塞IO特性。所以我们需要将上面的代码修改为如下就能正常工作了:

 

01 //output_me.js
02 var fs = require('fs'), fileContent = 'nothing';
03 fs.readFile(__filename, "utf-8"function(err, file) { 
04     if(err) { 
05         console.log(err);
06         return
07     }
08     fileContent = file;
09     

原文地址:https://www.cnblogs.com/wangkangluo1/p/2181041.html