win系统下nodejs安装及环境配置

第一步:下载安装文件
下载nodejs,官网:http://nodejs.org/download/,我这里下载的是node-v0.10.28-x86.msi,如下图:

第二步:安装nodejs
下载完成之后,双击”node-v0.10.28-x86.msi”,开始安装nodejs,自定义安装在D:\dev\nodejs下面。
在cmd控制台输入:node -v,控制台将打印出:v0.10.28,出现版本提示表示安装成功。
该引导步骤会将node.exe文件安装到D:\dev\nodejs\目录下,并将该目录添加进PATH环境变量。
第三步:npm安装
由于新版的nodejs已经集成了npm,所以之前npm也一并安装好了。同样可以使用cmd命令行输入”npm -v”来测试是否成功安装。如下图,出现版本提示表示安装成功。
第四步:安装相关环境
npm install express -g 
npm install jade -g
npm install mysql -g
默认情况下上述组件都是安装在D:\dev\nodejs\node_modules文件夹下,这也是nodejs相关组件的自动查找路径。
第五步:安装CoffeeScript
npm install coffee-script -g
确认安装的命令:coffee -v,出现版本号表示成功安装。
第六步:CoffeeScript测试实例
新建cs.js文件,输入:
for i in [0…5]
console.log “hello #{i}”
在该目录下运行”coffee cs.js” 输出:
D:\>coffee cs.js
hello 0
hello 1
hello 2
hello 3
hello 4
以上环境基本就配置完成。
补充说明:
所有命令都是-g进行全局安装的,这样安装的安装包都在当前用户下,在磁盘的所有其他地方都可以访问到,比较方面。否则安装在当前目录下,只能在当前目录下使用。
安装express问题
安装nodejs安装包后,通过npm安装express后,运行express提示” express”不是内部或外部命令,原因是版本问题,当前版本是4.0.0,改成3.5.0即可运行。
$ npm install -g express@3.5.0
全局安装在C:\Users\xdskg\AppData\Roaming\npm目录下。

Your environment has been set up for using Node.js 4.2.2 (x64) and npm.
C:\Users\Administrator>cd d:\Program Files\nodejs
C:\Users\Administrator>^D
‘’ 不是内部或外部命令,也不是可运行的程序
或批处理文件。
C:\Users\Administrator>D:
d:\Program Files\nodejs>npm express
Usage: npm <command>
where <command> is one of:
    access, add-user, adduser, apihelp, author, bin, bugs, c,
    cache, completion, config, ddp, dedupe, deprecate, dist-tag,
    dist-tags, docs, edit, explore, faq, find, find-dupes, get,
    help, help-search, home, i, info, init, install, issues, la,
    link, list, ll, ln, login, logout, ls, outdated, owner,
    pack, ping, prefix, prune, publish, r, rb, rebuild, remove,
    repo, restart, rm, root, run-script, s, se, search, set,
    show, shrinkwrap, star, stars, start, stop, t, tag, team,
    test, tst, un, uninstall, unlink, unpublish, unstar, up,
    update, upgrade, v, verison, version, view, whoami
npm <cmd> -h     quick help on <cmd>
npm -l           display full usage info
npm faq          commonly asked questions
npm help <term>  search for help on <term>
npm help npm     involved overview
Specify configs in the ini-formatted file:
    C:\Users\Administrator\.npmrc
or on the command line via: npm <command> –key value
Config info can be viewed via: npm help config
npm@2.14.7 d:\Program Files\nodejs\node_modules\npm
d:\Program Files\nodejs>npm jade
Usage: npm <command>
where <command> is one of:
    access, add-user, adduser, apihelp, author, bin, bugs, c,
    cache, completion, config, ddp, dedupe, deprecate, dist-tag,
    dist-tags, docs, edit, explore, faq, find, find-dupes, get,
    help, help-search, home, i, info, init, install, issues, la,
    link, list, ll, ln, login, logout, ls, outdated, owner,
    pack, ping, prefix, prune, publish, r, rb, rebuild, remove,
    repo, restart, rm, root, run-script, s, se, search, set,
    show, shrinkwrap, star, stars, start, stop, t, tag, team,
    test, tst, un, uninstall, unlink, unpublish, unstar, up,
    update, upgrade, v, verison, version, view, whoami
npm <cmd> -h     quick help on <cmd>
npm -l           display full usage info
npm faq          commonly asked questions
npm help <term>  search for help on <term>
npm help npm     involved overview
Specify configs in the ini-formatted file:
    C:\Users\Administrator\.npmrc
or on the command line via: npm <command> –key value
Config info can be viewed via: npm help config
npm@2.14.7 d:\Program Files\nodejs\node_modules\npm
d:\Program Files\nodejs>express shimo
‘express’ 不是内部或外部命令,也不是可运行的程序
或批处理文件。
d:\Program Files\nodejs>express myapp
‘express’ 不是内部或外部命令,也不是可运行的程序
或批处理文件。
d:\Program Files\nodejs>npm mysql
Usage: npm <command>
where <command> is one of:
    access, add-user, adduser, apihelp, author, bin, bugs, c,
    cache, completion, config, ddp, dedupe, deprecate, dist-tag,
    dist-tags, docs, edit, explore, faq, find, find-dupes, get,
    help, help-search, home, i, info, init, install, issues, la,
    link, list, ll, ln, login, logout, ls, outdated, owner,
    pack, ping, prefix, prune, publish, r, rb, rebuild, remove,
    repo, restart, rm, root, run-script, s, se, search, set,
    show, shrinkwrap, star, stars, start, stop, t, tag, team,
    test, tst, un, uninstall, unlink, unpublish, unstar, up,
    update, upgrade, v, verison, version, view, whoami
npm <cmd> -h     quick help on <cmd>
npm -l           display full usage info
npm faq          commonly asked questions
npm help <term>  search for help on <term>
npm help npm     involved overview
Specify configs in the ini-formatted file:
    C:\Users\Administrator\.npmrc
or on the command line via: npm <command> –key value
Config info can be viewed via: npm help config
npm@2.14.7 d:\Program Files\nodejs\node_modules\npm
d:\Program Files\nodejs>npm -v
2.14.7
d:\Program Files\nodejs>npm install coffee-script -g
C:\Users\Administrator\AppData\Roaming\npm\coffee -> C:\Users\Administrator\AppD
ata\Roaming\npm\node_modules\coffee-script\bin\coffee
C:\Users\Administrator\AppData\Roaming\npm\cake -> C:\Users\Administrator\AppDat
a\Roaming\npm\node_modules\coffee-script\bin\cake
coffee-script@1.10.0 C:\Users\Administrator\AppData\Roaming\npm\node_modules\cof
fee-script
d:\Program Files\nodejs>npm install express -g
express@4.13.3 C:\Users\Administrator\AppData\Roaming\npm\node_modules\express
├── escape-html@1.0.2
├── cookie@0.1.3
├── merge-descriptors@1.0.0
├── array-flatten@1.1.1
├── utils-merge@1.0.0
├── cookie-signature@1.0.6
├── content-type@1.0.1
├── range-parser@1.0.3
├── serve-static@1.10.0
├── methods@1.1.1
├── vary@1.0.1
├── etag@1.7.0
├── fresh@0.3.0
├── content-disposition@0.5.0
├── parseurl@1.3.0
├── path-to-regexp@0.1.7
├── depd@1.0.1
├── qs@4.0.0
├── finalhandler@0.4.0 (unpipe@1.0.0)
├── proxy-addr@1.0.8 (forwarded@0.1.0, ipaddr.js@1.0.1)
├── debug@2.2.0 (ms@0.7.1)
├── on-finished@2.3.0 (ee-first@1.1.1)
├── send@0.13.0 (destroy@1.0.3, statuses@1.2.1, ms@0.7.1, mime@1.3.4, http-er
rors@1.3.1)
├── type-is@1.6.9 (media-typer@0.3.0, mime-types@2.1.7)
└── accepts@1.2.13 (negotiator@0.5.3, mime-types@2.1.7)
d:\Program Files\nodejs>npm install jade -g
C:\Users\Administrator\AppData\Roaming\npm\jade -> C:\Users\Administrator\AppDat
a\Roaming\npm\node_modules\jade\bin\jade.js
jade@1.11.0 C:\Users\Administrator\AppData\Roaming\npm\node_modules\jade
├── commander@2.6.0
├── character-parser@1.2.1
├── void-elements@2.0.1
├── mkdirp@0.5.1 (minimist@0.0.8)
├── constantinople@3.0.2 (acorn@2.6.4)
├── jstransformer@0.0.2 (is-promise@2.1.0, promise@6.1.0)
├── with@4.0.3 (acorn@1.2.2, acorn-globals@1.0.9)
├── clean-css@3.4.8 (commander@2.8.1, source-map@0.4.4)
├── transformers@2.1.0 (promise@2.0.0, css@1.0.8, uglify-js@2.2.5)
└── uglify-js@2.6.1 (async@0.2.10, uglify-to-browserify@1.0.2, source-map@0.5
.3, yargs@3.10.0)
d:\Program Files\nodejs>cd mo
d:\Program Files\nodejs\mo>coffee csjs
File not found: d:\Program Files\nodejs\mo\csjs
d:\Program Files\nodejs\mo>coffee cs.js
d:\Program Files\nodejs\mo\cs.js:1:17: error: unexpected newline
for i in [0…5]
                ^
d:\Program Files\nodejs\mo>coffee cs.js
d:\Program Files\nodejs\mo\cs.js:1:17: error: unexpected newline
for i in [0…5]
                ^
d:\Program Files\nodejs\mo>coffee cs.js
d:\Program Files\nodejs\mo\cs.js:1:17: error: unexpected newline
for i in [0…5]
                ^
d:\Program Files\nodejs\mo>coffee cs.js
d:\Program Files\nodejs\mo\cs.js:1:17: error: unexpected newline
for i in [0…5]
                ^
d:\Program Files\nodejs\mo>coffee cs.js
hello
d:\Program Files\nodejs\mo>coffee cs.js
d:\Program Files\nodejs\mo\cs.js:1:17: error: unexpected newline
for i in [0…5]
               ^
d:\Program Files\nodejs\mo>coffee cs.js
d:\Program Files\nodejs\mo\cs.js:1:1: error: reserved word ‘var’
var http = require(“http”);
^^^
d:\Program Files\nodejs\mo>express myapp
‘express’ 不是内部或外部命令,也不是可运行的程序
或批处理文件。
d:\Program Files\nodejs\mo>$ npm install -g express@3.5.0
‘$’ 不是内部或外部命令,也不是可运行的程序
或批处理文件。
d:\Program Files\nodejs\mo>npm install -g express@3.5.0
npm WARN deprecated static-favicon@1.0.0: use serve-favicon module
C:\Users\Administrator\AppData\Roaming\npm\express -> C:\Users\Administrator\App
Data\Roaming\npm\node_modules\express\bin\express
express@3.5.0 C:\Users\Administrator\AppData\Roaming\npm\node_modules\express
├── methods@0.1.0
├── debug@0.8.1
├── merge-descriptors@0.0.2
├── cookie-signature@1.0.3
├── range-parser@1.0.0
├── fresh@0.2.2
├── buffer-crc32@0.2.1
├── cookie@0.1.1
├── mkdirp@0.3.5
├── commander@1.3.2 (keypress@0.1.0)
├── send@0.2.0 (mime@1.2.11)
└── connect@2.14.1 (qs@0.6.6, response-time@1.0.0, morgan@1.0.0, static-favic
on@1.0.0, vhost@1.0.0, raw-body@1.1.3, connect-timeout@1.0.0, basic-auth-connect
@1.0.0, pause@0.0.1, method-override@1.0.0, serve-static@1.0.2, bytes@0.2.1, err
orhandler@1.0.0, csurf@1.0.0, cookie-parser@1.0.1, express-session@1.0.2, compre
ssion@1.0.0, serve-index@1.0.1, multiparty@2.2.0)
d:\Program Files\nodejs\mo>

第四步:创建一个工程
现在已经有express
键入:express myapp (myapp是随意起的工程名称)
你会发现多了一个 C:\Program Files\nodejs\myapp 目录
默认情况下:里会自动创建 
这几个文件,不做解释,相信有过开发经验的同学都能一眼明了。
复制node_modules到myapp下面
环境搭建到此完工,下面做一个demo测试!
在myapp下新建helloworld.js
复制代码 代码如下:
var http = require(“http”); 
http.createServer(function(request, response) { 
response.writeHead(200, {“Content-Type”: “text/plain”}); 
response.write(“Hello World”); 
response.end(); 
}).listen(8888); 
console.log(“nodejs start listen 8888 port!”);
进入node.js command prompt 命令窗口,进入C:\Program Files\nodejs\myapp目录
键入node helloworld.js
发现输出 :Hello World

先来设置与远程地址的关联,Git remote:
很多人对GIT GUI客户端是非常不屑一顾的,但我非常喜欢GUI的方便快捷,也不用记忆冗杂的命令,本文简单的介绍了几种免费的Windows下的GIT客户端,方便大家使用。
Git for Windows 这个是最常见的GIT客户端了,非常简洁,常用的功能也都有,VisualStudio推荐的第三方工具就是它。
网页版本的linux/Unix客户端webshell
webshell是一个在网页上在线管理linux/unix操作系统的客户端,界面操作效果和著名的xshell一样; 所以取名为webshell。 使用方法:在linux/unix安装好nodejs以及部分模块环境之后,拷贝源码到服务器,进入目录, 执行node app 打开http://127.0.0.1:9000/index.htm就可以看到效果了。 因为需要随时随地管理服务器,看到nodejs比较方便实现所以拿nodejs实现了一个,代码挺少的,感兴趣的同学可以完善一下。 下载地址: https://github.com/Einsy/webshell
node.js学习入门示例博客分类: 
node.js学习入门示例博客分类: 
  这些天有点儿空闲,学习了一下node.js。先把《Node.js开发指南》书中的博客例子调通了,费了挺大的劲儿,因为好多插件出了新的版本,而新版本中有的函数、方法又失效了。 
  自已又练习着做了一个例子,个人记账系统。主要是想在手机上用,所以界面做得很简单。 
  解决了以下一些问题:express使用、bootstrap排版布局、mongodb模糊查询、mongodb统计(group/mapReduce)、session处理、req.flash方法使用等、路由设置等。花了不少的心思。 
  例子中用到的插件的版本: 
  connect-flash@0.1.1 
  connect-mongo@0.4.0 
  ejs@0.8.5 
  express@3.4.8 
  mongodb@1.3.23 
  Bootstrap V3.0.3 
  贴几张系统运行的图片,有图有真相嘛。 
 
 
 
 
 
  核心代码贴一下: 
一、app.js 
Javascript代码  
  1. /** 
  1.  * Module dependencies. 
  1.  */  
  1.   
  1. var express = require(‘express’);  
  1. var http = require(‘http’);  
  1. var path = require(‘path’);  
  1. var util=require(‘util’);  
  1.   
  1. var routes = require(‘./routes’);  
  1. //var User = require(‘./modules/user.js’);    
  1. var settings=require(‘./Settings’);  
  1.   
  1. var MongoStore = require(‘connect-mongo’)(express);  
  1. var flash = require(‘connect-flash’);  
  1.   
  1. var app = express();  
  1.   
  1. //app.set(‘appTitle’,’老王个人记账系统’);  
  1. app.locals.gAppTitle = settings.appName;  
  1. //这个没有使用  
  1. app.locals.gPageSize = settings.pageSize;  
  1. // all environments  
  1. app.set(‘port’, process.env.PORT || 8484);  
  1. app.set(‘views’, path.join(__dirname, ‘views’));  
  1. app.set(‘view engine’, ‘ejs’);  
  1. app.use(express.favicon());  
  1. app.use(express.logger(‘dev’));  
  1. app.use(express.json());  
  1. app.use(express.bodyParser());  
  1. app.use(express.urlencoded());  
  1. app.use(express.methodOverride());  
  1. app.use(express.cookieParser());  
  1. app.use(flash());  
  1. app.use(express.session({  
  1.     “secret”:settings.cookieSecret,  
  1.     “store”:new MongoStore({  
  1.         db:settings.db  
  1.     })  
  1. }));  
  1.   
  1. app.use(function(req, res, next){  
  1.   //跟踪;  
  1.   //console.log(“req.method=”+req.method);  
  1.   //console.log(“req.url=”+req.url);  
  1.   //console.log(“req.originalUrl=”+req.originalUrl);  
  1.   var url = req.originalUrl;  
  1.   //简单地定义一个登录拦截器  
  1.   if ((url == “/month” || url==”/stat” || url==’/list’ || url==’/record’) && !req.session.user) {  
  1.       console.log(“登录拦截器提示:必须登录,才能执行此项操作。”);  
  1.       req.flash(‘error’, ‘请先登录。’);  
  1.       return res.redirect(“/login”);  
  1.   }  
  1.     
  1.   res.locals.user = req.session.user;  
  1.     
  1.   var error = req.flash(‘error’);  
  1.   res.locals.error = error.length?error:null;  
  1.   //console.log(“转移flash中的error值:”+error);  
  1.     
  1.   var success = req.flash(‘success’);  
  1.   res.locals.success = success.length?success:null;  
  1.   //console.log(“转移flash中的success值:”+success);  
  1.     
  1.   res.locals.session = req.session;  
  1.   next();  
  1. });  
  1.   
  1. app.use(app.router);  
  1. app.use(express.static(path.join(__dirname, ‘public’)));  
  1. //console.log(util.inspect(app));  
  1.   
  1. // development only  
  1. if (‘development’ == app.get(‘env’)) {  
  1.   app.use(express.errorHandler());  
  1. }  
  1.   
  1. //console.log(‘注册路由.’);  
  1.   
  1. routes(app);  
  1.   
  1.   
  1. http.createServer(app).listen(app.get(‘port’), function(){  
  1.     console.log();  
  1.     console.log();  
  1.     console.log(‘/**************************************************/’);  
  1.     console.log(‘/*  我的第一个NODE.JS例子。BY 隔壁老王 2014-3-29  */’);  
  1.     console.log(‘/*   欢迎访问我的博客:http://wallimn.iteye.com   */’);  
  1.     console.log(‘/**************************************************/’);  
  1.     console.log(‘============服务启动成功,监听端口:’ + app.get(‘port’)+”============”);  
  1. });  
二、路由处理(routes\index.js) 
Javascript代码  
  1. var crypto = require(‘crypto’);  
  1. var User = require(‘../modules/user.js’);     
  1. var Consume = require(‘../modules/consume.js’);  
  1. /* 
  1.  * GET home page. 
  1.  */  
  1.   
  1. module.exports = function(app) {  
  1.     app.get(‘/’,function(req, res){  
  1.       res.render(‘index’, { title: ‘首页’ });  
  1.       /* 
  1.         res.render(‘login’,{ 
  1.             title:’用户登录’, 
  1.         }); 
  1.       */  
  1.       //res.redirect(‘/login’);  
  1.     });  
  1.   
  1.       
  1.     app.get(‘/record’,function(req,res){  
  1.         var user = req.session.user;  
  1.         if(!user){  
  1.             req.flash(‘error’, ‘用户未登录,请登录。’);  
  1.             return res.redirect(‘/login’);  
  1.         }  
  1.   
  1.         Consume.get(user.name,{limit:16}, function(err, records) {  
  1.             if (err) {  
  1.                 req.flash(‘error’, err);  
  1.                 return res.redirect(‘/error’);  
  1.             }  
  1.             res.render(‘record’, {  
  1.                 title: user.name,  
  1.                 consumes: records,  
  1.             });  
  1.         });  
  1.     });  
  1.       
  1.     //预处理,如果通过,再进行下一个。  
  1.     app.post(‘/record’,checkLogin);  
  1.   
  1.     app.post(‘/record’, function(req, res) {  
  1.         var currentUser = req.session.user;  
  1.         var record = new Consume();  
  1.         record.loadFromReq(currentUser.name, req.body);  
  1.         record.save(function(err) {  
  1.             if (err) {  
  1.                 req.flash(‘error’, err);  
  1.                 return res.redirect(‘/’);  
  1.             }  
  1.             req.flash(‘success’, ‘发表成功’);  
  1.             res.redirect(‘/record’);  
  1.         });  
  1.     });  
  1.   
  1.     //这个应该去掉。留在这里当个后门吧  
  1.     //可以查看其他用户的数据  
  1.     app.get(‘/u/:user’, function(req, res) {  
  1.         var username = req.params.user;  
  1.         if (!username) {  
  1.             req.flash(‘error’, ‘未指定用户’);  
  1.             return res.redirect(‘/error’);  
  1.         }  
  1.   
  1.         Consume.get(username,{limit:0}, function(err, records) {  
  1.             if (err) {  
  1.                 req.flash(‘error’, err);  
  1.                 return res.redirect(‘/error’);  
  1.             }  
  1.             console.log(records);  
  1.             res.render(‘list’, {  
  1.                 title: username,  
  1.                 consumes: records,  
  1.             });  
  1.         });  
  1.     });  
  1.       
  1.     app.get(‘/del/:id’, function(req, res) {  
  1.         var id = req.params.id;  
  1.         if (!id) {  
  1.             req.flash(‘error’, ‘未指定要删除的记录ID’);  
  1.             return res.redirect(‘/error’);  
  1.         }  
  1.           
  1.         console.log(“准备删除记账记录,_id=”+id);  
  1.         Consume.del(id, function(err, records) {  
  1.             if (err) {  
  1.                 req.flash(‘error’, err);  
  1.                 return res.redirect(‘/error’);  
  1.             }  
  1.             res.redirect(‘/record’);;  
  1.         });  
  1.     });  
  1.       
  1.     app.get(‘/logout’,function(req,res){  
  1.         req.session.user = null;  
  1.         req.flash(‘success’,’登出成功’);  
  1.         res.redirect(‘/login’);  
  1.     });  
  1.       
  1.     app.get(‘/list’,function(req,res){  
  1.         var user = req.session.user;  
  1.         if(!user){  
  1.                 req.flash(‘error’, “您没有登录,请登录。”);  
  1.                 console.log(“没有登录,重定向的登录界面。”);  
  1.                 return res.redirect(‘/login’);  
  1.         }  
  1.         Consume.get(user.name,{limit:0}, function(err, records) {  
  1.             if (err) {  
  1.                 req.flash(‘error’, err);  
  1.                 return res.redirect(‘/error’);  
  1.             }  
  1.             res.render(‘list’, {  
  1.                 title: user.name,  
  1.                 consumes: records,  
  1.             });  
  1.         });  
  1.     });  
  1.       
  1.     app.post(‘/search’,function(req,res){  
  1.         var user = req.session.user;  
  1.         if(!user){  
  1.                 req.flash(‘error’, “您没有登录,请登录。”);  
  1.                 return res.redirect(‘/login’);  
  1.         }  
  1.         var keyword = req.body.keyword;  
  1.         console.log(“搜索关键字:”+keyword);  
  1.         Consume.get(user.name,{limit:0,keyword:keyword}, function(err, records) {  
  1.             if (err) {  
  1.                 req.flash(‘error’, err);  
  1.                 return res.redirect(‘/error’);  
  1.             }  
  1.             res.render(‘record’, {  
  1.                 title: user.name,  
  1.                 consumes: records,  
  1.             });  
  1.         });  
  1.     });  
  1.       
  1.     app.get(‘/stat’,function(req,res){  
  1.         var user = req.session.user;  
  1.         Consume.stat(user.name, function(err, results) {  
  1.             if (err) {  
  1.                 req.flash(‘error’, err);  
  1.                 return res.redirect(‘/error’);  
  1.             }  
  1.             res.render(‘stat’, {  
  1.                 title: user.name,  
  1.                 results: results,  
  1.             });  
  1.         });  
  1.     });  
  1.       
  1.     app.get(‘/month’,function(req,res){  
  1.         var user = req.session.user;  
  1.         Consume.month(user.name, function(err, results) {  
  1.             if (err) {  
  1.                 req.flash(‘error’, err);  
  1.                 return res.redirect(‘/error’);  
  1.             }  
  1.             res.render(‘stat’, {  
  1.                 title: user.name,  
  1.                 results: results,  
  1.             });  
  1.         });  
  1.     });  
  1.       
  1.     app.get(‘/error’,function(req,res){  
  1.         res.render(‘error’);  
  1.     });  
  1.   
  1.     //处理用户登录。  
  1.     app.post(‘/login’,function(req,res){  
  1.         var md5=crypto.createHash(‘md5’);  
  1.         var password = md5.update(req.body.password).digest(‘hex’);  
  1.           
  1.         User.get(req.body.username,function(err,user){  
  1.             if(!user){  
  1.                 req.flash(‘error’,’用户不存在’);  
  1.                 return res.redirect(‘/login’);  
  1.             }  
  1.               
  1.             if(user.password!=password){  
  1.                 req.flash(‘error’,’用户口令错误’);  
  1.                 return res.redirect(‘/login’);  
  1.             }  
  1.               
  1.             req.session.user = user;  
  1.             req.flash(‘success’,’登入成功’);  
  1.             //res.redirect(‘/’);  
  1.             res.redirect(‘/record’);  
  1.         });  
  1.     });  
  1.   
  1.     app.get(‘/login’,function(req,res){  
  1.         res.render(‘login’,{  
  1.             title:’用户登录’,  
  1.         });  
  1.     });  
  1.   
  1.     app.get(‘/reg’,function(req,res){  
  1.           
  1.         res.render(‘reg’,{  
  1.             title:’用户注册’  
  1.         });  
  1.     });  
  1.   
  1.     app.post(‘/reg’,function(req,res){  
  1.         if(req.body[‘password-repeat’]!=req.body[‘password’]){  
  1.             req.flash(‘error’,’两次输入的口令不一致!’);  
  1.             return res.redirect(‘/reg’);  
  1.         }  
  1.           
  1.         var md5=crypto.createHash(‘md5’);  
  1.         var password = md5.update(req.body.password).digest(‘hex’);  
  1.           
  1.         var newUser = new User({  
  1.             name:req.body.username,  
  1.             password:password,  
  1.         });  
  1.           
  1.         User.get(newUser.name,function(err,user){  
  1.             if(user)  
  1.                 err=’同名用户已经存在,请更换名字.’;  
  1.             if(err){  
  1.                 req.flash(‘error’,err);  
  1.                 return res.redirect(‘/reg’);  
  1.             }  
  1.               
  1.             newUser.save(function(err){  
  1.                 if(err){  
  1.                     req.error=err;  
  1.                     return res.redirect(‘/reg’);  
  1.                 }     
  1.                 req.session.user = newUser;  
  1.                 req.flash(‘success’,’注册成功!’);  
  1.                 res.redirect(‘/record’);  
  1.             });  
  1.         });  
  1.     });  
  1.   
  1.     //测试函数  
  1.     app.get(‘/hello’,function(req,res){  
  1.         res.send(‘The time is ‘+new Date().toString());  
  1.     });  
  1.   
  1.     //测试函数  
  1.     app.get(‘/sayhello’,function(req,res){  
  1.         res.send(‘hello ‘+req.params.username);  
  1.     });  
  1.       
  1. };  
  1.   
  1. //检查是否登入.  
  1. function checkLogin(req, res, next) {  
  1.     if (!req.session.user) {  
  1.         req.flash(‘error’, ‘尚未登录,无法操作。’);  
  1.         return res.redirect(‘/error’);  
  1.     }  
  1.     next();  
  1. }  
  1.   
  1. function checkNotLogin(req, res, next) {  
  1.     if (req.session.user) {  
  1.         req.flash(‘error’, ‘已登入’);  
  1.         return res.redirect(‘/’);  
  1.     }  
  1.     next();  
  1. }  
三、消费数据处理(modules\consume.js) 
Javascript代码  
  1. var mongodb = require(‘./db’);  
  1. var BSON = require(‘mongodb’).BSONPure;  
  1. var util=require(‘util’);  
  1.   
  1.   
  1. function toObjectId(id){  
  1.     console.log(“转换值:”+id);  
  1.     if( id==”” || id==”null” || id==”undefined” || id==undefined || id==null)return null;  
  1.     return BSON.ObjectID.createFromHexString(id);  
  1. }  
  1.   
  1. function Consume(username, consumeDate,consumeSubject,consumeAmount,consumeRemark, time)  
  1. {  
  1.     //加载时要单独赋值  
  1.     this._id=null;  
  1.       
  1.     this.userName = username;  
  1.     this.consumeDate = consumeDate;  
  1.     this.consumeSubject = consumeSubject;  
  1.     this.consumeAmount = consumeAmount;  
  1.     this.consumeRemark = consumeRemark;  
  1.   
  1.     if (time)  
  1.     {  
  1.         this.time = time;  
  1.     }  
  1.     else  
  1.     {  
  1.         this.time = new Date();  
  1.     }  
  1.       
  1. };  
  1. module.exports = Consume;  
  1.   
  1. Consume.prototype.loadFromReq = function loadFromReq(username,reqBody,time){  
  1.     //自动进行了ID类型的转换。  
  1.     this._id = toObjectId(reqBody._id);  
  1.     this.userName = username;  
  1.     this.consumeDate = reqBody.consumeDate;  
  1.     this.consumeSubject = reqBody.consumeSubject;  
  1.     this.consumeAmount = reqBody.consumeAmount;  
  1.     this.consumeRemark = reqBody.consumeRemark;  
  1.   
  1.     if (time)  
  1.     {  
  1.         this.time = time;  
  1.     }  
  1.     else  
  1.     {  
  1.         this.time = new Date();  
  1.     }  
  1. }  
  1.   
  1. Consume.prototype.save = function save(callback)  
  1. {  
  1.     // 存入 Mongodb 的文档  
  1.     var record =   
  1.     {  
  1.         _id:this._id,  
  1.         userName: this.userName,   
  1.         consumeDate: this.consumeDate,   
  1.         consumeSubject: this.consumeSubject,   
  1.         consumeAmount: this.consumeAmount,   
  1.         consumeRemark: this.consumeRemark,   
  1.         time: this.time,   
  1.     };  
  1.     console.log(‘保存,记录日期:’+record.consumeDate);  
  1.     mongodb.open(function(err, db){  
  1.         if (err)  
  1.         {  
  1.             return callback(err);   
  1.         }  
  1.         // 读取 posts 集合  
  1.         db.collection(‘consume’, function(err, collection){  
  1.             if (err)  
  1.             {  
  1.                 mongodb.close(); return callback(err);   
  1.             }  
  1.   
  1.             // 插入  
  1.             /* 
  1.             collection.insert(record, {safe: true} , function(err, post){ 
  1.                 mongodb.close(); callback(err, post);  
  1.             });  
  1.             */  
  1.              
  1.            console.log(“插入或更新,判断依据_id=”+record._id);  
  1.            if(record._id==null){  
  1.                delete record._id;  
  1.                console.log(“删除_id,record._id=”+record._id);  
  1.            }  
  1.            collection.update({_id:(record._id?record._id:’no-record’)}, record, {upsert:true,multi:false} , function(err, post){  
  1.                 mongodb.close(); callback(err, post);   
  1.             });   
  1.         });   
  1.     });  
  1. };  
  1.   
  1. //删除方法  
  1. Consume.del = function del(id,callback){  
  1.     mongodb.open(function(err,db){  
  1.         if (err){  
  1.             return callback(err);   
  1.         }  
  1.           
  1.         var query = {_id:BSON.ObjectID.createFromHexString(id)};  
  1.           
  1.         db.collection(‘consume’, function(err, collection){  
  1.             if (err){  
  1.                 mongodb.close();   
  1.                 return callback(err);   
  1.             }  
  1.   
  1.             collection.remove(query,{safe:true},function(err,result){  
  1.                 mongodb.close();  
  1.                 if (err){  
  1.                     return callback(err);   
  1.                 }  
  1.                 console.log(“删除成功。”);  
  1.                 callback(null);   
  1.             }) ;  
  1.         });      
  1.     });  
  1. };  
  1.   
  1.   
  1.   
  1. Consume.get = function get(username,options, callback)  
  1. {  
  1.     mongodb.open(function(err, db){  
  1.         if (err){  
  1.             return callback(err);   
  1.         }  
  1.         // 读取 posts 集合  
  1.         db.collection(‘consume’, function(err, collection){  
  1.             if (err){  
  1.                 mongodb.close();  
  1.                 return callback(err);   
  1.             }  
  1.   
  1.             var query = {};  
  1.             if(options.keyword){  
  1.                 //var regx = new RegExp(“/”+options.keyword+”/”);  
  1.                 //注意,不用/  
  1.                 var regx = new RegExp(options.keyword);  
  1.                 //限制用户名,科目或者金额与输入关键相等  
  1.                 query={“$and”:[{userName:username},  
  1.                                {“$or”:[{consumeSubject:regx},  
  1.                                        {consumeDate:regx},  
  1.                                        {consumeAmount:options.keyword}  
  1.                                       ]  
  1.                                }]  
  1.                        };  
  1.             }  
  1.             else{  
  1.                 query.userName = username;   
  1.             }  
  1.             console.log(“搜索条件:”);  
  1.             console.log(query);  
  1.             if(!options.limit){  
  1.                 options.limit=0;  
  1.             }  
  1.             collection.find(query).sort({consumeDate:-1 }).limit(options.limit).toArray(function(err, docs){  
  1.                 mongodb.close();   
  1.                 if (err){  
  1.                     callback(err, null);   
  1.                 }  
  1.   
  1.                 var consumes = [];   
  1.                 docs.forEach(function(doc, index){  
  1.                     var record = new Consume(doc.userName, doc.consumeDate,doc.consumeSubject,doc.consumeAmount,doc.consumeRemark, doc.time);  
  1.                     record._id = doc._id;  
  1.                     consumes.push(record);   
  1.                 });   
  1.                 callback(null, consumes);   
  1.             });   
  1.         });   
  1.     });  
  1. };  
  1.   
  1.   
  1.   
  1. Consume.stat = function stat(username, callback)  
  1. {  
  1.     mongodb.open(function(err, db){  
  1.         if (err){  
  1.             return callback(err);   
  1.         }  
  1.         // 读取 posts 集合  
  1.         db.collection(‘consume’, function(err, collection){  
  1.             if (err){  
  1.                 mongodb.close();  
  1.                 return callback(err);   
  1.             }  
  1.   
  1.             var reduce = function(obj,prev){  
  1.                     prev.amount += isNaN(obj.consumeAmount)?0:Number(obj.consumeAmount);  
  1.                     prev.count++;  
  1.             };  
  1.           
  1.             collection.group(  
  1.                 [ ‘consumeSubject’ ],  
  1.                 {userName:username},  
  1.                 {count:0,amount:0},  
  1.                 reduce,  
  1.                 function(err, result){  
  1.                     mongodb.close();   
  1.                     if (err){  
  1.                         callback(err, null);   
  1.                     }  
  1.                     else{  
  1.                         console.log(result[0]);  
  1.                         var amount = 0,count=0;  
  1.                         result.forEach(function (item,index){  
  1.                             amount += item.amount;  
  1.                             count += item.count;  
  1.                         });  
  1.                         result.push({consumeSubject:’【合计】’,count:count,amount:amount});  
  1.                         callback(null, result);   
  1.                     }  
  1.             });  
  1.         });   
  1.     });  
  1. };  
  1.   
  1. Consume.month = function month(username, callback)  
  1. {  
  1.     mongodb.open(function(err, db){  
  1.         if (err){  
  1.             return callback(err);   
  1.         }  
  1.         // 读取 posts 集合  
  1.         db.collection(‘consume’, function(err, collection){  
  1.             if (err){  
  1.                 mongodb.close();  
  1.                 return callback(err);   
  1.             }  
  1.               
  1.             var map = function(){  
  1.                 emit(this.consumeDate.substr(0,7),{amount:this.consumeAmount,count:1});  
  1.             };  
  1.               
  1.             var reduce = function(key,vals){  
  1.                 var val = 0,count=0;  
  1.                 for(var i=0; i<vals.length;i++){  
  1.                     val += isNaN(vals[i].amount)?0:Number(vals[i].amount);  
  1.                     count++;  
  1.                 }  
  1.                 return {amount:val,count:count};  
  1.             }  
  1.               
  1.             console.log(“统计:”+username);  
  1.             collection.mapReduce(  
  1.                 map,  
  1.                 reduce,  
  1.                 {out: {replace : ‘temp’, readPreference : ‘secondary’, query:{userName:username}}},  
  1.                 function(err, collection){  
  1.                     if (err){  
  1.                         mongodb.close();   
  1.                         callback(err, null);   
  1.                     }  
  1.                     else{  
  1.                         //console.log(collection);  
  1.                         /* 
  1.                         var amount = 0,count=0; 
  1.                         result.forEach(function (item,index){ 
  1.                             amount += item.amount; 
  1.                             count += item.count; 
  1.                         }); 
  1.                         result.push({consumeSubject:’【合计】’,count:count,amount:amount}); 
  1.                         */  
  1.                           
  1.                         var results = [];  
  1.                         collection.find().toArray(function(err,docs){  
  1.                             docs.forEach(function(item,idx){  
  1.                                 console.log(item);  
  1.                                 //为了共用结果页面,统一使用consumeSubject  
  1.                                 results.push({consumeSubject:item._id,amount:item.value.amount,count:item.value.count});  
  1.                             });  
  1.                             mongodb.close();  
  1.                             callback(null, results);   
  1.                         });  
  1.                     }  
  1.             });  
  1.         });   
  1.     });  
  1. };  
  全部源码见附件。 
  另,2014-04-02 
  系统开发好了之后,找了个服务器部署了一下,老婆用得不错,原来不太喜欢记账,现在记账很积极。我就又把系统完善了一下,增加了翻页、权限控制功能,将几个按钮修改成图标,布局更紧凑了一些,使用全局变量保存系统名称,方便修改。 
Joursion 85 5月7日 提问
  • 关注 19 关注
  • 收藏 2 收藏,1.1k 浏览
问题对人有帮助,内容完整,我也想知道答案0问题没有实际价值,缺少关键内容,没有改进余地
表示刚入门,不知道用什么软件写,最好是那种带补全,带提示,类似VS的软件
学习环境:ubuntu
  •  
  •  
  • 2 评论
  •  
  • 更多
20 个回答
答案对人有帮助,有参考价值0答案没帮助,是错误的答案,答非所问
采纳
micblo 321 5月14日 回答
WebStorm蛮不错的。
喜欢它的代码提示,轻松进行版本控制。
可以自动生成Express项目。
而且又不算很贵,趁打折期间买更划算。
如果是学生或者开源项目可以去申请免费许可证。
  •  
  • 更多
答案对人有帮助,有参考价值2答案没帮助,是错误的答案,答非所问
心不在焉 561 5月7日 回答
vim + neocomplete

 

发表评论