为什么要用node.js它又有什么优势呢?一个新的技术被大家喜爱那么它就必然有它的优势,那么下面我们就来简单把它和php做一个对比
1 . Node.js 他用的是JavaScript引擎,那么注定它是单线程 ,使用异步方法开辟多个任务,无需像php等待上个任务线程使用结束之后给下个使用,
PHP也是单线程但是它借用Apache服务器提供多线程服务


var http = require ( ‘http‘ ) ;
http.createServer ( function handler ( req , res ) {
res.writeHead ( 200 , {‘Content-Type‘ : ‘text/html ; charset=utf-8‘ });
if (req.url !== ‘/favicon.ico‘) {
str = "" ; //随机字符 - 20k
//随机生成文件
fileName = String.fromCharCode ( Math. floor ( 65 + ( Math. random () * ( 122 - 65 )))) + ".txt" ;
//str 赋值
for ( i = 0; i < 200000; i++ ){
n = Math. floor ( 65 + ( Math. random () * ( 122 - 65 )) ) ;
str += String. fromCharCode ( n ) ;
}
//写入
var fs = require ( ‘fs‘ ) ;//操作文件模块
//写入内容
fs.writeFile ( fileName,str,function ( err, fd ) {
if ( err ) throw err ; //如果错误则抛出错误
//读取文件 并展示的页面
fs.readFile ( fileName , function( err, data ){
if ( err ) throw err ;
res.write(data);//输出
res.end (‘‘) ; // 结束
}) ;
}
);
}
}).listen(8000) ;
console. log ( ‘success:8000‘ ) ;
PHP
1 <?php
2
3 $str = "" ; //随机字符串
4 // 文本名字
5 $fileName = chr ( rand ( 0 , 57 ) + 65 ).‘.txt‘ ;
6
7 for ( $i = 0 ; $i < 200000 ; $i ++ ){
8
9 $n = rand ( 0 , 57 ) + 65 ;
10 $str = $str . chr ( $n ) ;
11 }
12
13 //写入
14
15 file_put_contents( $fileName , $str ) ;
16
17 $result = file_get_contents ( $fileName ) ;
18
19 echo $result ;
20 ?>
原文:http://www.cnblogs.com/aeexiaoqiang/p/6529281.html