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