
有沒聽過Node.js?筆者也是最近才知道有這東西。熟悉javascript的人都知道,javascript是client side的scripting language。那node.js怎麼又會跟server side有關呢?其實,node.js是一個基於V8(google 的javascript engine),event driven的server side執行環境。
這說明了你可以用javascript來編寫server side的application,而且它是event driven的。
它不是multi-process或multi-thread,而是event driven,因此效能也就更好,開發出來的application也更scalable。 multi-thread是有代價的,一般需要更多的memory,因此不夠scalable。雖是single-thread,但所有的I/O都是asyn及event driven,因此它都是non-blocking的。它十分適合用於編寫多人同時使用的server應用,例如chat server。
以下是官方的一個hello world web server範例。只要幾行javascript就可以完成!這比一般以socket編寫易得多!
var http = require("http");
http.createServer(function(req, res){
res.writeHead("Hello world");
res.end("Hello World");
}).listen(8080, "Server is running at http://127.0.0.1:8080");
如要運行,請先安裝好node.js,windows用戶可下載node.exe,其他平台請參考Node.js官網。
Node.js官網:http://nodejs.org
筆者以後會為大家介紹更多的node.js應用。