日期:2014-05-16  浏览次数:20397 次

Node.js学习小结

Nodejs作为服务端Javascript。它的最大特点是采用异步式I/O与事件驱动的架构设计。对于高并发的解决方案,传统的架构是多线程模型,也就是为每个业务逻辑提供一个系统线程,通过系统线程切换来弥补同步式I/O调用时的时间开销。Node.js使用的是单线程模型,对于所有I/O都采用异步式的请求方式,避免频繁的上下文切换

下载地址:http://nodejs.org/download/

学习教程: ? Nodejs开发指南

以下以mac为例,下载Mac版的pkg,然后进行安装。

例1.简单应用

创建一个js,并用node运行它。helloworld.js内容为console.log("Hello World");

然后运行helloworld.js,命令如下:node helloworld.js

?

例2.web应用

创建一个server.js文件,内容为:

var http = require("http");

http.createServer(function(request,response){

response.writeHead(200,{"Content-Type":"text/plain"});

response.write("Hello World");

response.end();}).listen(8888);

然后启动服务:node server.js

?

例3.同步和异步读文件

bteki-MacBook-Pro:nodeFile b$ node readfile.js?

end.

This is good girl.so you must...

?

bteki-MacBook-Pro:nodeFile b$ vi readfilesync.js

bteki-MacBook-Pro:nodeFile b$ cat readfile.js?

var fs = require('fs');

fs.readFile('file.txt','utf-8',function(err,data){

if(err){

?console.error(err);

}else{

?console.log(data);

}

});

console.log('end.');

bteki-MacBook-Pro:nodeFile b$ node readfilesync.js?

This is good girl.so you must...

?

end.

bteki-MacBook-Pro:nodeFile b$ cat readfilesync.js?

var fs=require('fs');

var data=fs.readFileSync('file.txt','utf-8');

console.log(data);

console.log('end.');

=========================================================

1、由于nodejs是单线程,当主线程异常时,会导致整个进程挂掉。forever可以解决该问题,它

将确保永远运行。线程死亡时,会自动重启。

?

$ sudo npm install forever -


                        
友情链接: 爱易网 云虚拟主机技术 云服务器技术 程序设计技术 开发网站 APP开发教程
Copyright © 2013-2024 爱易网页 当前在线:652人  网站在6时42分1秒内访问总人数:98035人 当前 30.16%  粤ICP备18100884号-2