官方安裝說明:https://github.com/joyent/node/wiki/Installation
這條路徑是從源碼出發,在各個操作系統上自行編譯,適合需要定製版本的人。
若只想快點跑起來,直接去下載頁拿編譯好的包:https://nodejs.org/download/。我的機器是 Windows,選的是 Windows Installer (.msi) 32-bit 版本,一路下一步裝完即可。
打開你最順手的編輯器,新建 helloworld.js,寫入一行:
console.log("Hello World");
保存後打開 Node.js 的命令行窗口,把文件直接拖進窗口自動填入路徑,前面補上 node 執行:
node C:\path\to\helloworld.js
控制台輸出終究只是自娛,Node.js 真正的舞台在網絡服務。同一個文件改成:
var http = require('http');
server = http.createServer(function (req, res) {
res.writeHeader(200, {"Content-Type": "text/plain"});
res.end("Hello World\n");
})
server.listen(8000);
console.log("httpd start @8000");
按前面的方式運行 node helloworld.js,控制台打出 httpd start @8000,說明服務已在 8000 端口監聽。打開瀏覽器訪問 https://localhost:8000/,頁面上出現 Hello World——你的第一個 Node.js 服務就此上線。
對比一下就能體會差異:同樣的功能,用傳統的 LAMP 組合往往需要配置 Apache 與 vhost,而這裡只有五行情真意切的代碼。