在Linux系統中搭建Node.js開發環境的簡單步驟講解,linuxnode.js
1. Linux安裝node.js
ubuntu:
sudo apt-get install nodejs npm
centos:
yum install nodejs npm
更詳細的安裝參見:https://github.com/joyent/node/wiki/Installation
npm為類似PHP中Pear的包管理器
2. 開始使用node.js
用文字編輯器建立hello.js寫入以下內容
console.log('hello world');
開啟命令列輸入
$ node hello.js
你會看到輸出
$ hello world
console.log是最常用的輸出指令
3. 建立HTTP伺服器
理解node.js架構
像PHP的架構模型為:
瀏覽器--》HTTP伺服器(apache、nginx)--》PHP解譯器
而在node.js應用中,node.js採用:
瀏覽器--》node.js這種架構
建立HTTP伺服器:建立一個app.js檔案,內容如下:
var http = require('http');http.createServer(function(req, res){ res.writeHead(200,{'Content-Type': 'text/html'}); res.write('</pre><h1>node.js</h1><pre>'); res.end('hello world ');}).listen(3000);console.log("http server is listening at port 3000.");
運行
$ node app.js
開啟瀏覽器開啟http://127.0.0.1:3000查看結果
該程式調用了node.js提供的http模組,對所有的Http請求回覆同樣的內容並監聽3000連接埠。運行這個指令碼後不會立刻退出,必須按下ctro+c才會停止,這是因為listen函數建立了事件監聽器。
4. 調試指令碼
node.js指令碼修改後,必須停止原程式,重新運行,才能看到變化。
用包管理器安裝supervisor工具。
$ npm install -g supervisor
以後通過
$ supervisor app.js
來運行node.js程式,它會檢測程式碼變化,自動重啟程式。
注意:安裝時需要獲得root許可權。
您可能感興趣的文章:
- 在linux中使用包管理器安裝node.js
- Node.js入門教程:在windows和Linux上安裝配置Node.js圖文教程
- 在NodeJS中啟用ECMAScript 6小結(windos以及Linux)
- 在Linux上用forever實現Node.js項目自啟動
- linux開機啟動nodemanager步驟