Nodejs+Extjs+Mongodb开发第一天 Nodejs环境搭建

来源:互联网 发布:不想找女朋友 知乎 编辑:程序博客网 时间:2024/04/25 14:46

一、装备


我个人PC环境是Ubuntu14+JDK7,所以下面的步骤及问题也是基于此进行及产生的。

 

二、Nodejs及npm的安装


这个安装的过程在网上有很多教程,这里就不详细讲了。

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. $ sudo apt-get install python   
  2.   
  3. $ sudo apt-get install build-essential   
  4.   
  5. $ sudo apt-get install gcc   
  6.   
  7. $ sudo apt-get install g++   
  8.   
  9. $ sudo apt-get install nodejs  
  10.   
  11. $ sudo apt-get install npm  

查看Nodejs的版本,网上很多教程都写的是:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. node -v  


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

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. nodejs -v  


终端显示:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. v0.10.25  


经测试,ubuntu下Nodejs的命令是nodejs,而windows平台的是node。


查看npm版本是

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. npm -v   
  2. 1.3.10  

三、使用npm来安装supervisor工具及express框架

1、supervisor 


简单介绍:


在开发 Node.js 实现的 HTTP 应用时会发现,无论你修改了代码的哪一部份,都必须终止 Node.js 再重新运行才会奏效。这是因为 Node.js 只有在第一次引用到某部份时才会去解析脚 本文件,以后都会直接访问内存,避免重复载入。Node.js的这种设计虽然有利于提高性能,却不利于开发调试,因 为我们在开发过程中总是希望修改后立即看到效果,而不是每次都要终止进程并重启。

supervisor 可以帮助你实现这个功能,它会监视你对代码的改动,并自动重启 Node.js。


a) 全局安装 (我的选择)

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. npm install supervisor -gd  


b) 安装在当前文件夹下 

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. npm install supervisor  


安装成功后,命令行会提示 npm info ok

 

-g代表安装到NODE_PATH的lib里面,而-d代表把相依性套件也一起安装。如果沒有-g的话会安装目前所在的目录(会建立一个node_modules的文件夹)。

 

通过以下命令了查看supervisor的帮助文档,

 

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. supervisor -hellp   

 

终端显示:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /usr/bin/env: node: 没有那个文件或目录  


经查找后,发现npm在安装模块的时候,会把源码及执行文件分开。

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /usr/local/lib/node_modules  源码目录  
  2. /usr/local/bin  执行文件目录  


注意:这里也是和网上的大部分教程不一样的地方,网上的教程都说源码及执行文件都是放在/usr/local/lib/node_modules 目录下的,估计是npm版本不同的原因。

 

找到并查看supervisor的执行文件:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. #!/usr/bin/env node   
  2. var path = require("path")   
  3.   , fs = require("fs")   
  4.   , args = process.argv.slice(1)   
  5.   
  6. var arg, base;   
  7. do arg = args.shift();   
  8. while ( fs.realpathSync(arg) !== __filename   
  9.   && (base = path.basename(arg)) !== "node-supervisor"   
  10.   && base !== "supervisor"   
  11.   && base !== "supervisor.js"   
  12. )   
  13.   
  14. require("./supervisor").run(args)  


看到supervisor的介绍,我们很容易得知,这个小模块的主要功能有两个:

1、关闭正在执行的项目

2、启动前面关闭的项目


这里报的错误是没有找到node,而且很清楚地发现执行文件的第一行使用的命令是!/usr/bin/env node ,回想前面查看Nodejs版本的命令。项目启动用到的应该是Nodejs本身的命令nodejs,

于是将这一行修改如下进行尝试,问题得到解决。

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. #!/usr/bin/env nodejs  

终端显示supervisor的帮助如下:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. Node Supervisor is used to restart programs when they crash.   
  2.   
  3. It can also be used to restart programs when a *.js file changes.   
  4.   
  5.   
  6.   
  7. Usage:   
  8.   
  9.   supervisor [options] <program>   
  10.   
  11.   supervisor [options] -- <program> [args ...]   
  12.   
  13.   
  14.   
  15. Required:   
  16.   
  17.   <program>   
  18.   
  19.     The program to run.   
  20.   
  21.   
  22.   
  23. Options:   
  24.   
  25.   -w|--watch <watchItems>   
  26.   
  27.     A comma-delimited list of folders or js files to watch for changes.   
  28.   
  29.     When a change to a js file occurs, reload the program   
  30.   
  31.     Default is '.'   
  32.   
  33.   
  34.   
  35.   -i|--ignore <ignoreItems>   
  36.   
  37.     A comma-delimited list of folders to ignore for changes.   
  38.   
  39.     No default   
  40.   
  41.   
  42.   
  43.   -p|--poll-interval <milliseconds>   
  44.   
  45.     How often to poll watched files for changes.   
  46.   
  47.     Defaults to Node default.   
  48.   
  49.   
  50.    
  51.   -e|--extensions <extensions>   
  52.   
  53.     Specific file extensions to watch in addition to defaults.   
  54.   
  55.     Used when --watch option includes folders   
  56.   
  57.     Default is 'node,js'   
  58.   
  59.   
  60.   
  61.   -x|--exec <executable>   
  62.   
  63.     The executable that runs the specified program.   
  64.   
  65.     Default is 'node'   
  66.   
  67.   
  68.   
  69.   --debug   
  70.   
  71.     Start node with --debug flag.   
  72.   
  73.   
  74.   
  75.   --debug-brk[=port]   
  76.   
  77.     Start node with --debug-brk[=port] flag.   
  78.   
  79.   
  80.   
  81.   --harmony   
  82.   
  83.     Start node with --harmony flag.   
  84.   
  85.   
  86.   
  87.   -n|--no-restart-on error|exit   
  88.   
  89.     Don't automatically restart the supervised program if it ends.   
  90.   
  91.     Supervisor will wait for a change in the source files.   
  92.   
  93.     If "error", an exit code of 0 will still restart.   
  94.   
  95.     If "exit", no restart regardless of exit code.   
  96.   
  97.   
  98.   
  99.   --force-watch   
  100.   
  101.     Use fs.watch instead of fs.watchFile.   
  102.    
  103.     This may be useful if you see a high cpu load on a windows machine.   
  104.   
  105.   
  106.   
  107.   -h|--help|-?   
  108.   
  109.     Display these usage instructions.   
  110.   
  111.   
  112.   
  113.   -q|--quiet   
  114.   
  115.     Suppress DEBUG messages   
  116.   
  117.   
  118.   
  119.   -V|--verbose   
  120.   
  121.     Show extra DEBUG messages   
  122.   
  123.   
  124.   
  125. Examples:   
  126.   
  127.   supervisor myapp.js   
  128.   
  129.   supervisor myapp.coffee   
  130.   
  131.   supervisor -w scripts -e myext -x myrunner myapp   
  132.   
  133.   supervisor -- server.js -h host -p port   


注意:根据帮助文档,查看supervisor的命令是supervisor -V 。命令中的V是大写,安装过程中我发现windows下小写也行,但在我的ubuntu14的环境下必须是大写。

2、express 

a) 全局安装 (我的选择)

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. npm install express -gd  


b) 安装在当前文件夹下 

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. npm install  express  

在安装完后,express与supervisor一样,也存在Nodejs命令不符合的问题,同样的方式找到执行文件进行修改此命令即可。

 

安装完了express,如果版本是4.0及以上的话,还要安装另外一个模块,express才能使用。

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. sudo npm install -g express-generator  

四、项目的建立及执行

1、新建一个名称为test的项目

2、使用express框架

cd 到test目录的上级目录,执行以下命令

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. express -e test  

执行完后,回到项目目录查看:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. node_modules, 存放所有的项目依赖库。   
  2. package.json,项目依赖配置及开发者信息   
  3. app.js,程序启动文件   
  4. public,静态文件(css,js,img)   
  5. routes,路由文件(MVC中的C,controller)   
  6. views,页面文件(Ejs模板)   
  7. bin ,存放默认启动的脚本  

package.json :

 

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. {  
  2.   "name": "pcrm",  
  3.   "version": "0.0.1",  
  4.   "private": true,  
  5.   "scripts": {  
  6.     "start": "node ./bin/www"  
  7.   },  
  8.   "dependencies": {  
  9.     "express": "~4.2.0",  
  10.     "static-favicon": "~1.0.0",  
  11.     "morgan": "~1.0.0",  
  12.     "cookie-parser": "~1.0.1",  
  13.     "body-parser": "~1.0.0",  
  14.     "debug": "~0.7.4",  
  15.     "ejs": "~0.8.5"  
  16.   }  
  17. }  

 

app.js:

 

[javascript] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. var express = require('express');  
  2. var path = require('path');  
  3. var favicon = require('static-favicon');  
  4. var logger = require('morgan');  
  5. var cookieParser = require('cookie-parser');  
  6. var bodyParser = require('body-parser');  
  7.    
  8. var routes = require('./routes/index');  
  9. var users = require('./routes/users');  
  10.    
  11. var app = express();  
  12.    
  13. // view engine setup  
  14. app.set('views', path.join(__dirname, 'views'));  
  15. app.set('view engine''ejs');  
  16.    
  17. app.use(favicon());  
  18. app.use(logger('dev'));  
  19. app.use(bodyParser.json());  
  20. app.use(bodyParser.urlencoded());  
  21. app.use(cookieParser());  
  22. app.use(express.static(path.join(__dirname, 'public')));  
  23.    
  24.    
  25. app.use('/', routes);  
  26. app.use('/users', users);  
  27.    
  28. /// catch 404 and forward to error handler  
  29. app.use(function(req, res, next) {  
  30.     var err = new Error('Not Found');  
  31.     err.status = 404;  
  32.     next(err);  
  33. });  
  34.    
  35. /// error handlers  
  36.    
  37. // development error handler  
  38. // will print stacktrace  
  39. if (app.get('env') === 'development') {  
  40.     app.use(function(err, req, res, next) {  
  41.         res.status(err.status || 500);  
  42.         res.render('error', {  
  43.             message: err.message,  
  44.             error: err  
  45.         });  
  46.     });  
  47. }  
  48.    
  49. // production error handler  
  50. // no stacktraces leaked to user  
  51. app.use(function(err, req, res, next) {  
  52.     res.status(err.status || 500);  
  53.     res.render('error', {  
  54.         message: err.message,  
  55.         error: {}  
  56.     });  
  57. });  
  58.    
  59. module.exports = app;  


bin/www:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. #!/usr/bin/env node  
  2. var debug = require('debug')('pcrm');  
  3. var app = require('../app');  
  4.    
  5. app.set('port', process.env.PORT || 3000);  
  6.    
  7. var server = app.listen(app.get('port'), function() {  
  8.   debug('Express server listening on port ' + server.address().port);  
  9. });  


3、执行

cd到test目录下

 

执行方法1:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. npm start  

终端显示异常:

 

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. > test@0.0.1 start /home/benben/workspace/test  
  2. > node ./bin/www  
  3.    
  4. sh: 1: node: not found  
  5. npm ERR! weird error 127  
  6. npm WARN This failure might be due to the use of legacy binary "node"  
  7. npm WARN For further explanations, please read  
  8. /usr/share/doc/nodejs/README.Debian  
  9.    
  10. npm ERR! not ok code 0  

 

还是node命令的问题,修改package.json 文件中的

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. "start": "node ./bin/www"  为  "start": "nodejs ./bin/www"  


 

bin/www文件中的

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. #!/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中添加如下代码 

[javascript] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. app.listen(3000);   


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

 

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. nodejs app.js  
 

得到同样的结果。

 

 执行方法3:

 使用supervisor进行热部署的执行方便调试

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. supervisor app.js  


终端显示异常:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. Running node-supervisor with  
  2.   program 'app.js'  
  3.   --watch '.'  
  4.   --extensions 'node,js'  
  5.   --exec 'node'  
  6.    
  7. Starting child process with 'node app.js'  
  8. execvp(): No such file or directory  
  9. Watching directory '/home/benben/workspace/pcrm' for changes.  
  10.    
  11. events.js:72  
  12.         throw er; // Unhandled 'error' event  
  13.               ^  
  14. Error: spawn ENOENT  
  15.     at errnoException (child_process.js:988:11)  
  16.     at Process.ChildProcess._handle.onexit (child_process.js:779:34)  


 

这里解决的过程就不详细说了,重点是--exec 'node'这个,会发现supervisor执行的还是node命令,而不是nodejs。修改supervisor源文件目录下的supervisor.js文件

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. if (!executor) {   
  2.    executor = (programExt === "coffee" || programExt === "litcoffee") ? "coffee" : "node";   
  3.  }  

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. if (!executor) {   
  2.    executor = (programExt === "coffee" || programExt === "litcoffee") ? "coffee" : "nodejs";   
  3.  }  


再次执行成功,项目修改后,Nodejs也会自动重启。


五、IDE的选择

一开始选择的是nodeclipse,但用起来确实不怎么完善。于是选择WebStorm。

关于IDE使用及Nodejs的使用,在以后使用的过程中会再发文章记录。


FROM: http://blog.csdn.net/jrainbow/article/details/38845639

0 0