Nodejs第一天 環境及出現的問題

來源:互聯網
上載者:User

標籤:nodejs   supervisor   express   npm   app.js   

一、裝備

我個人PC環境是Ubuntu14+JDK7,所以下面的步驟及問題也是基於此進行及產生的。

 

二、Nodejs及npm的安裝

這個安裝的過程在網上有很多教程,這裡就不詳細講了。

$ sudo apt-get install python $ sudo apt-get install build-essential $ sudo apt-get install gcc $ sudo apt-get install g++ $ sudo apt-get install nodejs$ sudo apt-get install npm

查看Nodejs的版本,網上很多教程都寫的是:

node -v


但一直node命令找不到的異常,使用以下命令執行成功:

nodejs -v


終端顯示:

v0.10.25


經測試,ubuntu下Nodejs的命令是nodejs,而windows平台的是node。


查看npm版本是

npm -v 1.3.10

三、使用npm來安裝supervisor工具及express架構

1、supervisor 
簡單介紹:

在開發 Node.js 實現的 HTTP 應用時會發現,無論你修改了代碼的哪一部份,都必須終止 Node.js 再重新運行才會奏效。這是因為 Node.js 只有在第一次引用到某部份時才會去解析腳 本檔案,以後都會直接存取記憶體,避免重複載入。Node.js的這種設計雖然有利於提高效能,卻不利於開發調試,因 為我們在開發過程中總是希望修改後立即看到效果,而不是每次都要終止進程並重啟。
supervisor 可以協助你實現這個功能,它會監視你對代碼的改動,並自動重啟 Node.js。


a) 全域安裝 (我的選擇)

npm install supervisor -gd


b) 安裝在當前檔案夾下 

npm install supervisor


安裝成功後,命令列會提示 npm info ok

 

-g代表安裝到NODE_PATH的lib裡面,而-d代表把相依性套件也一起安裝。如果沒有-g的話會安裝目前所在的目錄(會建立一個node_modules的檔案夾)。

 

通過以下命令了查看supervisor的協助文檔,

 

supervisor -hellp 

 

終端顯示:

/usr/bin/env: node: 沒有那個檔案或目錄


經尋找後,發現npm在安裝模組的時候,會把源碼及執行檔案分開。

/usr/local/lib/node_modules  源碼目錄/usr/local/bin  執行檔案目錄


注意:這裡也是和網上的大部分教程不一樣的地方,網上的教程都說源碼及執行檔案都是放在/usr/local/lib/node_modules 目錄下的,估計是npm版本不同的原因。

 

找到並查看supervisor的執行檔案:

#!/usr/bin/env node var path = require("path")   , fs = require("fs")   , args = process.argv.slice(1) var arg, base; do arg = args.shift(); while ( fs.realpathSync(arg) !== __filename   && (base = path.basename(arg)) !== "node-supervisor"   && base !== "supervisor"   && base !== "supervisor.js" ) require("./supervisor").run(args)


看到supervisor的介紹,我們很容易得知,這個小模組的主要功能有兩個:

1、關閉正在執行的項目

2、啟動前面關閉的項目


這裡報的錯誤是沒有找到node,而且很清楚地發現執行檔案的第一行使用的命令是!/usr/bin/env node ,回想前面查看Nodejs版本的命令。項目啟動用到的應該是Nodejs本身的命令nodejs,

於是將這一行修改如下進行嘗試,問題得到解決。

#!/usr/bin/env nodejs

終端顯示supervisor的協助如下:

Node Supervisor is used to restart programs when they crash. It can also be used to restart programs when a *.js file changes. Usage:   supervisor [options] <program>   supervisor [options] -- <program> [args ...] Required:   <program>     The program to run. Options:   -w|--watch <watchItems>     A comma-delimited list of folders or js files to watch for changes.     When a change to a js file occurs, reload the program     Default is '.'   -i|--ignore <ignoreItems>     A comma-delimited list of folders to ignore for changes.     No default   -p|--poll-interval <milliseconds>     How often to poll watched files for changes.     Defaults to Node default.    -e|--extensions <extensions>     Specific file extensions to watch in addition to defaults.     Used when --watch option includes folders     Default is 'node,js'   -x|--exec <executable>     The executable that runs the specified program.     Default is 'node'   --debug     Start node with --debug flag.   --debug-brk[=port]     Start node with --debug-brk[=port] flag.   --harmony     Start node with --harmony flag.   -n|--no-restart-on error|exit     Don't automatically restart the supervised program if it ends.     Supervisor will wait for a change in the source files.     If "error", an exit code of 0 will still restart.     If "exit", no restart regardless of exit code.   --force-watch     Use fs.watch instead of fs.watchFile.      This may be useful if you see a high cpu load on a windows machine.   -h|--help|-?     Display these usage instructions.   -q|--quiet     Suppress DEBUG messages   -V|--verbose     Show extra DEBUG messages Examples:   supervisor myapp.js   supervisor myapp.coffee   supervisor -w scripts -e myext -x myrunner myapp   supervisor -- server.js -h host -p port 


注意:根據協助文檔,查看supervisor的命令是supervisor -V 。命令中的V是大寫,安裝過程中我發現windows下小寫也行,但在我的ubuntu14的環境下必須是大寫。

2、express 

a) 全域安裝 (我的選擇)

npm install express -gd


b) 安裝在當前檔案夾下 

npm install  express

在安裝完後,express與supervisor一樣,也存在Nodejs命令不符合的問題,同樣的方式找到執行檔案進行修改此命令即可。

 

安裝完了express,如果版本是4.0及以上的話,還要安裝另外一個模組,express才能使用。

sudo npm install -g express-generator

四、項目的建立及執行1、建立一個名稱為test的項目2、使用express架構

cd 到test目錄的上級目錄,執行以下命令

express -e test

執行完後,回到項目目錄查看:

node_modules, 存放所有的項目依賴庫。 package.json,項目依賴配置及開發人員資訊 app.js,程式開機檔案 public,靜態檔案(css,js,img) routes,路由檔案(MVC中的C,controller) views,分頁檔(Ejs模板) bin ,存放預設啟動的指令碼

package.json :

 

{  "name": "pcrm",  "version": "0.0.1",  "private": true,  "scripts": {    "start": "node ./bin/www"  },  "dependencies": {    "express": "~4.2.0",    "static-favicon": "~1.0.0",    "morgan": "~1.0.0",    "cookie-parser": "~1.0.1",    "body-parser": "~1.0.0",    "debug": "~0.7.4",    "ejs": "~0.8.5"  }}

 

app.js:

 

var express = require('express');var path = require('path');var favicon = require('static-favicon');var logger = require('morgan');var cookieParser = require('cookie-parser');var bodyParser = require('body-parser'); var routes = require('./routes/index');var users = require('./routes/users'); var app = express(); // view engine setupapp.set('views', path.join(__dirname, 'views'));app.set('view engine', 'ejs'); app.use(favicon());app.use(logger('dev'));app.use(bodyParser.json());app.use(bodyParser.urlencoded());app.use(cookieParser());app.use(express.static(path.join(__dirname, 'public')));  app.use('/', routes);app.use('/users', users); /// catch 404 and forward to error handlerapp.use(function(req, res, next) {    var err = new Error('Not Found');    err.status = 404;    next(err);}); /// error handlers // development error handler// will print stacktraceif (app.get('env') === 'development') {    app.use(function(err, req, res, next) {        res.status(err.status || 500);        res.render('error', {            message: err.message,            error: err        });    });} // production error handler// no stacktraces leaked to userapp.use(function(err, req, res, next) {    res.status(err.status || 500);    res.render('error', {        message: err.message,        error: {}    });}); module.exports = app;


bin/www:

#!/usr/bin/env nodevar debug = require('debug')('pcrm');var app = require('../app'); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() {  debug('Express server listening on port ' + server.address().port);});


3、執行

cd到test目錄下

 

執行方法1:

npm start

終端顯示異常:

 

> [email protected] start /home/benben/workspace/test> node ./bin/www sh: 1: node: not foundnpm ERR! weird error 127npm WARN This failure might be due to the use of legacy binary "node"npm WARN For further explanations, please read/usr/share/doc/nodejs/README.Debian npm ERR! not ok code 0

 

還是node命令的問題,修改package.json 檔案中的

 "start": "node ./bin/www"  為  "start": "nodejs ./bin/www"


 

bin/www檔案中的

#!/usr/bin/env node 為 #!/usr/bin/env nodejs

執行成功



npm是什麼東西呢?大部分的Java程式員都使用過Maven。而npm的職能與Maven相似,是Nodejs的包管理工具,可以使用它來下載包、查看檔案等功能用express建立的應用程式是一個符合CommonJS規範的一個nodejs包npm執行的時候會讀取目前的目錄的package.json檔案,這個也就是我上面那個bug出現的原因執行npm start其實是執行package.json中的script對應的對象中的start屬性所對應的命令。

 

所以其實如果吧package.json中的start改成test或者其他字串,然後你在終端敲上npm test/或者其他,程式照樣會運行 。

 

其實package.json就是一個設定檔,只是我們之前用的xml格式,但是在nodejs用的是json可以,簡單容易理解。從package.json我們可以看出來npm start其實執行的是./bin/www裡面是建立一個伺服器然後監聽3000連接埠,所以我們可以在瀏覽器中通過輸入"localhost:3000"來訪問應用程式。


執行方法2:

npm start 是啟用的 /bin/www檔案裡的指令碼 

如果你想用nodejs 啟動服務 可以在app.js中添加如下代碼 

app.listen(3000); 


注意:上面的語句得加在module.exports = app;之前。

 

nodejs app.js
 

得到同樣的結果。

 

 執行方法3:

 使用supervisor進行熱部署的執行方便調試

supervisor app.js


終端顯示異常:

Running node-supervisor with  program 'app.js'  --watch '.'  --extensions 'node,js'  --exec 'node' Starting child process with 'node app.js'execvp(): No such file or directoryWatching directory '/home/benben/workspace/pcrm' for changes. events.js:72        throw er; // Unhandled 'error' event              ^Error: spawn ENOENT    at errnoException (child_process.js:988:11)    at Process.ChildProcess._handle.onexit (child_process.js:779:34)


 

這裡解決的過程就不詳細說了,重點是--exec ‘node‘這個,會發現supervisor執行的還是node命令,而不是nodejs。修改supervisor源檔案目錄下的supervisor.js檔案

 if (!executor) {     executor = (programExt === "coffee" || programExt === "litcoffee") ? "coffee" : "node";   }

 if (!executor) {     executor = (programExt === "coffee" || programExt === "litcoffee") ? "coffee" : "nodejs";   }


再次執行成功,項目修改後,Nodejs也會自動重啟。


五、IDE的選擇一開始選擇的是nodeclipse,但用起來確實不怎麼完善。於是選擇WebStorm。
關於IDE使用及Nodejs的使用,在以後使用的過程中會再發文章記錄。






Nodejs第一天 環境及出現的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.