閱讀245 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Nodejs+Extjs+Mongodb開發第一天 Nodejs環境搭建

一、裝備


我個人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 setup
app.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 handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});
 
/// error handlers
 
// development error handler
// will print stacktrace
if (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 user
app.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 node
var 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

終端顯示異常:

 

> test@0.0.1 start /home/benben/workspace/test
> node ./bin/www
 
sh: 1: node: not found
npm ERR! weird error 127
npm 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 directory
Watching 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的使用,在以後使用的過程中會再發文章記錄。






最後更新:2017-04-03 05:40:04

  上一篇:go 貧血模型與領域架構模式
  下一篇:go 限製字符串輸入——正則表達式(VB.NET)