什么是node.js
- 編寫高性能網(wǎng)絡服務器的JavaScript工具包
- 單線程、異步、事件驅(qū)動
(就是來1w個請求,來一個請求就給這個請求開辟一個內(nèi)存塊來處理?
(事件驅(qū)動就是例如來一個事件,然后有一個回調(diào),等事件(請求?)結(jié)束,處理回調(diào)? - 特點: 快,耗內(nèi)存多
- 異步消耗內(nèi)存測試:網(wǎng)上一個百萬級并發(fā)測試,未優(yōu)化的情況下 1M的連接消耗了16G的內(nèi)存
node.js 的劣勢和解決方案
- 默認不支持多核,可用cluster解決
- 默認不支持服務器集群,node-http-proxy可解決
- 使用nginx做負載均衡,靜態(tài)由nginx處理,動態(tài)由node.js處理
- forever或node-cluster實現(xiàn)災難恢復
(以上這一些名詞還待詳細學習)
安裝
安裝 node.js 官網(wǎng)下載
測試是否安裝成功
npm -v
node -v
hello world
var http = require('http');
// http 創(chuàng)建一個服務
// request - 瀏覽器向服務器請求發(fā)出的對象
// response - 服務器向瀏覽器寫回的對象
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
console.log('訪問');
response.write('hello,world');
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
/*
啟動服務
cmd下執(zhí)行:
node n1_hello.js
瀏覽器訪問:http://localhost:8000
*/
瀏覽器:
可以看到雖然輸出了文字,但是瀏覽器還一直在loading
因為缺少了一句response.end()
,http協(xié)議實際還未結(jié)束
01_hello_loading.png
增加response.end
var http = require('http');
// http 創(chuàng)建一個服務
// request - 瀏覽器向服務器請求發(fā)出的對象
// response - 服務器向瀏覽器寫回的對象
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
console.log('訪問');
// write 輸出但http協(xié)議未執(zhí)行完畢
response.write('hello,world');
response.end('hell,世界');//不寫則沒有http協(xié)議尾,但寫了會產(chǎn)生兩次訪問
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
response.end中也可以輸入
然后從控制臺中可以看到,輸入了兩次"訪問"
01_hello_console.png
這是因為瀏覽器會再次訪問 favicon 這個資源
01_hello_chrome.png
清除二次訪問
var http = require('http');
// http 創(chuàng)建一個服務
// request - 瀏覽器向服務器請求發(fā)出的對象
// response - 服務器向瀏覽器寫回的對象
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url!=="/favicon.ico"){ //清除第2此訪問
console.log('訪問');
// write 輸出但http協(xié)議未執(zhí)行完畢
response.write('hello,world');
response.end('hell,世界');//不寫則沒有http協(xié)議尾,但寫了會產(chǎn)生兩次訪問
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');