為什么要用node.js它又有什么優勢呢?一個新的技術被大家喜愛那么它就必然有它的優勢,那么下面我們就來簡單把它和php做一個對比
1 . Node.js 他用的是JavaScript引擎,那么注定它是單線程 ,使用異步方法開辟多個任務,無需像php等待上個任務線程使用結束之后給下個使用,
PHP也是單線程但是它借用Apache服務器提供多線程服務
2 . 高並發,大數據量怎么處理:
php : 優化sql ,用組件,用緩存,為了讓線程盡快結束,進行下一次任務
node:單線程 、異步、事件驅動
下面是他們處理事件,
php上下銜接依次執行,
node中因為運行速度很快並不會等待,所以如果后面用到前面返回的結果,就需要把后面的封裝起來,作為一個回調函數執行

node.js vs php
優點:
性能高(運行機制問題)
開發效率高(省不少優化的事)
應用范圍廣(可以開發桌面系統,electron框架)
缺點:
新、人少
中間件少
IDE不完善
node.js的劣勢和解決方案
1 默認不支持多核,但可以用cluster解決
2 默認不支持服務器集群,node-http-proxy可以解決
3 使用nginx做負載均衡,靜態的由nginx處理,動態的有node.js處理
4 forever或node-cluster實現災難恢復
下面是 一個數據測試
請求-->隨機創建內容是20k字符的文檔 -->讀取文檔 -->輸出
結果是 node所需的時間要遠小於php所用的時間
1 Node
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 ?>