express和mongoose基础

  • express里的几个概念
  • mongoose的2个方法

关于参数

  • req.query
  • req.body
  • req.params

关于rest

关于view render

关于mongoose的methods

关于mongoose的statics

总结

一句话,没有目标的时候向钱看,有目标就向前看。

有时间就多学点,没坏处

欢迎关注我的公众号【node全栈】

关于学习

关于学习

关于杂与专

杂是博的通俗叫法,好听的叫博,比如博士,学不好的应该叫“杂士”

这个问题已经讨论很多年了,我的推荐的做法

  • 特定领域博,不能全领域博,人不是万能的,也没有那么多时间,合作更重要
  • 专:做事尽全力去做,争取做到最好

举个例子,软件行业可以是特定领域,nodejs开发可以特定领域,前端也可以是,找准自己的兴趣点

忌讳的是:今天ps,明天3d,到最后还只是一个小写代码的。。。

是不是很可悲?

在国外,程序员都不承认自己是屌丝,是码农,码畜,我也很不理解为啥国内是这种想法

工资一月几钱到一月几万,甚至更多,大家有想过差别么?

如果没有关系,没有有钱的爹,又不能卖肾,就努力让自己多学点,多赚点

我的一句名言:“没有目标的时候向钱看,有目标就向前看”

现在算和平年代,创业潮,崇尚技术,最好的2种选择:1)经商,2)有一种拿的出手的技术

另外要说的一点是:什么都想做什么都做不好

大公司和小公司的学习差异

人还是要不断切换状态,聪明学习

在一家管理松散,到处都是混日子的公司,你最好的做法是学习,别人越是玩手段,混日子,你就越该学东西

  • 你会越来越厉害
  • 技术优越感
  • 一旦有事儿,你一定最快上位,那个时候就是别人求着你

但如果你在一个创业公司里,你就不能这样做,此时,你至少要装的很积极,每天假装100%的时间都放到工作上

  • 创业公司输不起
  • 同甘苦共富贵,不是能共富贵的就早点离开
  • 创业公司的技术通常是最直接的,最容易学到精华的
  • 不要排斥学不同的东西,比如做nodejs的,学学运维,学学os,没啥坏处

那么这2种公司里学习的差别在那里呢?

  • 乱的公司里,找东西学,不学的是傻子
  • 创业公司里把做的事儿当成学习(实战比自己玩进步的快),找东西学的是傻子

再换个角度讲:谁他妈愿意带着傻子一起玩?

IPO歪解

  • i=input 输入
  • p=process 处理
  • o=output 输出

这个相信大部分人都了解

我们在设计一个产品的时候,其实可以借鉴这个思路

比如i是用户创造的东西,比如发表xxx,点赞等等,是创造内容

p是运营的部分,纯用户创造的ugc会死的很难看,运营会精选,加入各种爆点,便于更好的玩起来

o是展现内容,是由用户创造 + 运营内容组成的。

得出的公式:(i + p)=o,对于产品的设计,数据流都是非常有帮助的。

另外对ipo进行分类会更有益处,思维导图非常容易出得。

其实“ipo”是为了真的ipo:

首次公开募股(Initial Public Offerings,简称IPO):是指一家企业或公司 [1] (股份有限公司)第一次将它的股份向公众出售(首次公开发行,指股份公司首次向社会公众公开招股的发行方式)。

歪解ipo的目的

  • 为了说明,学到得东西有的时候是可以活用的
  • 如果给知识插上想象的翅膀。。。

总结

一句话,没有目标的时候向钱看,有目标就向前看。

有时间就多学点,没坏处

欢迎关注我的公众号【node全栈】

如何选择nodejs和iojs?以及性能比较

如何选择nodejs和iojs?以及性能比较

有朋友问我:

初学nodejs,但是看到很多都转移去io.js,开源中国也有份测试说io性能更好,现在两者不知如何选择,望指教

看看iojs的官网 https://iojs.org/en/index.html

1.io.js is an npm compatible platform originally based on Node.js™.

这句话的重点在于基于nodejs,且兼容npm,所以它和node是一个根

2.Weekly Update – May 15th: io.js decides to join the Node Foundation

这句话说的是io.js绝对加入node基金会

这条新闻很有意思

https://medium.com/node-js-javascript/io-js-week-of-may-15th-9ada45bd8a28

As a first step, we will move from iojs organization to nodejs organization and will converge joyent/node gradually. We will continue to release io.js until the convergence have done.

我们会持续发布io.js,直到收编完成。

We will continue to release io.js until the convergence have done.

我们可以这样理解

  • 收编完成之后,还是要会回归node主分支的
  • 我们是斗气,joyent那边孙子如果不让步,我们就继续闹

看完了这段,估计大家已经知道怎么选择了

  • iojs早晚是要合并到nodejs里的,只是时间和形式的问题
  • 如果各位看看iojs的文档,它和nodejs的接口大部分是一样的,所以很少会有地雷

下面给出一篇英文比较iojs和node的性能的文章,如果看不懂,看图就够了

先给出node自己的0.10和0.12的比较

Performance Showdown: Node.js vs. io.js v2.0.0

We noted with some interest the recent announcement of the io.js v2.0.0 release candidate. This community fork of node.js promises a supported version of the V8 engine, along with a greatly increased frequency of commits to master vs. the parent project.

As we’ve mentioned before, we’re keen on these developments as Node.js powers the Raygun API nodes, and ensuring these can handle the highest loads with the lowest possible response times is crucial to providing a great service to our users. A previous blog post benchmarked Node.js vs. io.js, and with the advent of the V2 release of the latter, we’d like to revisit those benchmarks to see how it stacks up in various situations.

The set up

Same as before, the following are synthetic micro-benchmarks, caveat emptor, huge grain of salt, etc. However, the charts do provide some interesting food for thought, and may provide a springboard for you to perform your own real-world tests, and potentially gain a significant speedup.

The benchmarks were conducted with identical runs through ApacheBench on a 64-bit Ubuntu VM. The configuration was 20,000 requests with a concurrency level of 100, and the test results were averaged over five runs of this.

We benchmarked two versions of node, and two versions of io.js. For node, v0.10.38 (the last release of the .10 branch) was compared against v0.12.2 (the absolute latest version of node.js).

For io.js, we compared v1.8.1, the last release on the 1.x branch against the newest v2.0.0 release.

Raw JSON response

This test involved created a simple server with the http module, and setting it to return a JSON payload on request. The results were:

What is interesting to note is the performance drop from node 0.10 to 0.12, which io.js corrects on the 1.x branch – but then dominates with v2.0.0.

When sending a raw response, in this benchmark io.js v2.0.0 has a 14% speedup over node 0.12! They’ve even managed a 5% speedup over their own previous release. Not bad at all, but there’s more we can test.

Express.js

Express was and is still a very popular choice for quickly getting the backend of a web application up and running. Last time we documented some of the performance hit you take with it, but let’s see how it does under node 0.12 vs io.js v2.0.0:

There’s a 4.5% speedup when running this test on io.js v2.0.0 – pretty good for an older framework (considering how fast the JS ecosystem is moving)!

Koa.js on Node vs io.js

Many newer frameworks are competing for mindshare in the JS micro web framework space, however – we benchmarked some popular ones previously. One which we missed was Koa.js, which was in fact made by the authors of Express.js.

One of the huge benefits with Koa is that you can build code using ES6 features – including generators and the yield syntax which enable asynchronous code (no more callback hell). This benchmark was written using generators and run with the node –harmony flag enabled. The logic involved a simple bit of routing, and set the response to be an HTML fragment.

Let’s see how Koa does running on Node vs. io.js:

A 14.8% speedup from Node to the latest version of io.js – certainly worthy of note. If you’re looking at one of the latest generation of JS backend frameworks, it certainly pays to give io.js a look as out-of-the-box you get some rather impressive perf improvements. When running a cluster of VMs using the Node stack, depending on scale, that speedup may result in several fewer boxes needed and correspondingly less infrastructure costs – all for free.

总结

一句话,iojs性能比较nodejs好,看好nodejs的发展。

欢迎关注我的公众号【node全栈】

pre commit用法

pre-commit用法说明

Automatically install pre-commit hooks for your npm modules.

安装

npm install --save-dev pre-commit

示例package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
"name": "xxxxx",
"version": "1.0.0",
"description": "xxxxx =====",
"main": "index.js",
"scripts": {
"checkconflict":"ack '<<<<<<<'"
}
,

"pre-commit": [
"checkconflict"
],

"repository": {
"type": "git",
"url": "https://github.com/i5ting/xxxxx.git"
}
,

"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/i5ting/xxxxx/issues"
}
,

"homepage": "https://github.com/i5ting/xxxxx",
"devDependencies": {
"pre-commit": "0.0.9"
}

}

说明

  • pre-commit部分,说明依赖的scripts里的命令,比如例子我创建了一个checkconflict
  • 当我们git commit的时候就调用pre-commit部分

它可以干啥

  1. 检查冲突
  2. 提交前自己先测试
  3. 。。。

自己发挥吧

mongoose test

this is a test example project for mongoose!

准备工作

这部分主要是完成了构建项目骨架代码得任务,通过命令和少许文件更改,即可完成。

创建项目

express .

使用更快的npm源

测速

nrm test

选择速度快的源

nrm use cnpm

安装依赖包

npm install

添加更多有用依赖

npm install --save mongoose
npm install --save bcrypt

安装服务器自动重载模块

npm install --save-dev supervisor

安装测试模块

mkdir test
touch Gulpfile.js

npm install --save-dev mocha
npm install --save-dev chai
npm install --save-dev sinon
npm install --save-dev supertest
npm install --save-dev zombie

单元测试需要的各个模块说明

  • mocha(Mocha is a feature-rich JavaScript test framework running on node.js and the browser, making asynchronous testing simple and fun.)
  • chai(Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.)
  • sinon(Standalone test spies, stubs and mocks for JavaScript.)
  • zombie (页面事件模拟Zombie.js is a lightweight framework for testing client-side JavaScript code in a simulated environment. No browser required.)
  • supertest(接口测试 Super-agent driven library for testing node.js HTTP servers using a fluent API)

修改Gulpfile.js

  • auto test
  • 代码测试覆盖率
1
2
3
npm install --save-dev gulp
npm install --save-dev gulp-mocha
npm install --save-dev gulp-istanbul

创建gulpfilejs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var gulp = require('gulp');
var istanbul = require('gulp-istanbul');
var mocha = require('gulp-mocha');

gulp.task('test', function (cb) {
gulp.src(['db/**/*.js'])
.pipe(istanbul()) // Covering files
.on('finish', function () {
gulp.src(['test/*.js'])
.pipe(mocha())
.pipe(istanbul.writeReports()) // Creating the reports after tests runned
.on('end', cb);
});
});

gulp.task('default',['test'], function() {
gulp.watch(['./db/**/*','./test/**/*'], ['test']);
});

gulp.task('watch',['test'], function() {
gulp.watch(['./db/**/*','./test/**/*'], ['test']);
});

测试

1
node_modules/.bin/gulp

这时,你试试修改测试或源文件试试,看看会不会自动触发测试

当然,如果你喜欢只是测试一次,可以这样做

1
node_modules/.bin/gulp test

如果你不熟悉gulp,可以再这里https://github.com/i5ting/js-tools-best-practice/blob/master/doc/Gulp.md学习

修改package.json

1
2
3
4
 "scripts": {
"start": "./node_modules/.bin/supervisor ./bin/www",
"test": "./node_modules/.bin/mocha -u tdd"
},

todo

@小龙,写成一个一键脚本

test

TDD 流程是,先编写一个失败测试,然后编写应用代码让测试通过,最后再按需重构代码。因为很多测试工具都使用红色表示失败测试,使用绿色表示通过的测试,所以这个流程有时也叫“遇红-变绿-重构”循环。这一节我们先完成这个循环的第一步,编写一个失败测试,“遇红”。然后在变绿,重构。

创建db/user_model.js

此文件里编写用户相关的mongodb操作

  • Schema define
  • virtual attr
  • save pre callback
  • UserSchema.methods
  • UserSchema.statics
  • findOne
  • user hash password with salt
  • getAuthenticated

创建test/user_model.js

测试2个方法

  • #save()
  • #getAuthenticated()

测试代码基本结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
describe('UserModel', function(){
before(function() {
// runs before all tests in this block
})
after(function(){
// runs after all tests in this block
})
beforeEach(function(){
// runs before each test in this block
})
afterEach(function(){
// runs after each test in this block
})

describe('#save()', function(){
it('should return sang_test2 when user save', function(done){
。。。
})
})
})

生命周期说明

  • before
  • after
  • beforeEach
  • afterEach

上面这段代码是向测试UserModel#save()方法是否符合需求。

断言

断言都是单元测试的核心

断言作为Assert类的静态方法。如果一个断言失败,方法的调用不会返回值,并且会报告一个错误。

如果一个测试包含多个断言,那些紧跟失败断言的断言都不会执行,因为此原因,通常每个测试方法最好只有一个断言。每个方法可以无消息调用,也可以是带有一个简单文本消息调用,或者带有一个消息以及参数调用。在最后一种情况下,使用了一个提供的文本以及参数来格式化消息。

目前流行的断言基本分为3类

  • assert风格
  • should风格
  • expect风格

没有好坏之分,只是看个人习惯

这里使用chai这个库,它支持3种风格的断言,非常方便

Chai has several interfaces that allow the developer to choose the most comfortable. The chain-capable BDD styles provide an expressive language & readable style, while the TDD assert style provides a more classical feel.

1
2
3
var assert = require('chai').assert;
var expect = require('chai').expect;
require('chai').should();

具体用法请查看http://chaijs.com/文档

测试命令

启动mongodb服务

mongod

服务器启动

npm start

测试

npm test

自动测试和代码测试覆盖率法1:基于gulp

  • auto test
  • 代码测试覆盖率
1
2
3
npm install --save-dev gulp
npm install --save-dev gulp-mocha
npm install --save-dev gulp-istanbul

创建gulpfilejs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var gulp = require('gulp');
var istanbul = require('gulp-istanbul');
var mocha = require('gulp-mocha');

gulp.task('test', function (cb) {
gulp.src(['db/**/*.js'])
.pipe(istanbul()) // Covering files
.on('finish', function () {
gulp.src(['test/*.js'])
.pipe(mocha())
.pipe(istanbul.writeReports()) // Creating the reports after tests runned
.on('end', cb);
});
});

gulp.task('default',['test'], function() {
gulp.watch(['./db/**/*','./test/**/*'], ['test']);
});

gulp.task('watch',['test'], function() {
gulp.watch(['./db/**/*','./test/**/*'], ['test']);
});

测试

1
node_modules/.bin/gulp

这时,你试试修改测试或源文件试试,看看会不会自动触发测试

当然,如果你喜欢只是测试一次,可以这样做

1
node_modules/.bin/gulp test

如果你不熟悉gulp,可以再这里https://github.com/i5ting/js-tools-best-practice/blob/master/doc/Gulp.md学习

自动测试和代码测试覆盖率法2:基于cli

首先安装依赖npm包

npm install --save-dev mocha
npm install --save-dev istanbul

在package.json里scripts增加

"test": "./node_modules/.bin/mocha --reporter spec",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot"

然后测试

npm test
npm run test-cov
npm run test-travis

这里想自动化会有点麻烦,还是建议解除gulp

如果不了npm run命令,请参阅 https://github.com/i5ting/npm-run-test

测试相关网址

更多

下面概念,请自行了解

  • TDD
  • BDD

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

版本历史

  • v0.1.0 初始化版本

作者

  • 桑世龙
  • 柯织
  • 黄小龙

欢迎fork和反馈

在issue提问或邮件shiren1118@126.com

License

this gem is released under the MIT License.

测试MongoDB

MongoDB

WARNING: soft rlimits too low” in MongoDB with Mac OS X

source

If you get this warning when you connect to mongo shell in Mac OX X:

** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
A simple way to fix this is setting the limit just before starting mongod with this:

ulimit -n 1024 && mongod

Or this:

launchctl limit maxfiles 1024 1024

But if you are running mongo in a development environment this shouldn’t be a problem, you can just ignore it.

This is a temporary and not very pretty fix. To make this permanent you have to add this to the/etc/launchd.conf file:

launchctl limit maxfiles 1024 1024

Now reboot to make changes effective.

You can see the actual values of the limits running this:

$ launchctl limit maxfiles
        maxfiles    1024           1024

Remember to restart your mongod process every time you change any value to see if it works.

url

http://i5ting.com/2014/04/start-a-new-nodejs-the-right-way/

http://mongoosejs.com/docs/index.html

自动reload代码:supervisor

安装

npm install --save supervisor

修改package.js

“scripts”: {
“start”: “./node_modules/.bin/supervisor ./bin/www”
}

然后

npm start

打印错误栈信息: stackman

He is like Batman, but for Node.js stack traces

https://github.com/watson/stackman

http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4#route-middleware

Welcome to Jekyll!

You’ll find this post in your _posts directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run jekyll serve --watch, which launches a web server and auto-regenerates your site when a file is updated.

To add new posts, simply add a file in the _posts directory that follows the convention YYYY-MM-DD-name-of-post.ext and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.

Jekyll also offers powerful support for code snippets:

1
2
3
4
5
def print_hi(name)
puts "Hi, #{name}"
end
print_hi('Tom')
#=> prints 'Hi, Tom' to STDOUT.

Check out the Jekyll docs for more info on how to get the most out of Jekyll. File all bugs/feature requests at Jekyll’s GitHub repo. If you have questions, you can ask them on Jekyll’s dedicated Help repository.

Welcome to Nodeonly!

原文地址

Node.js是极其流行的,且毫无疑问你可以用它可以做任何你见过的不可思议的工作。由于很多新鲜东西,所以入门会比较复杂一些:Node.js是灵活,强大的工具,它可以用于构建很多不同类型的项目,从服务器端应用到网站,到工具,几乎无所不能。当然,它还只是一个迅速串红的新兴的工具,同样一件事儿可以有非常多的办法去做,很难去说会用到什么工具或者流程。

在 Node.js
web开发社区有一件事是确定的,有2个经常用于构建新的web应用的库,它们分别是connect
和express。Connect是底层工具让你可以使用http协议或者其他网络协议进行会话。
Express让构建好的网站更加简单
,而且它是构建于Connect库之上的。

接下来我会给你们展示几个技巧,我发现的,可以帮助你们入Express的门,希望以此加快你使用Node构建web应用的速度,我也会通过这个教程作为我已发布的其他教程的入口,我不想告诉你它很难,相反我是试图帮你理解如何处理好。

当我们学完,我们会有一个express应用,它有 Less,
sessions, test runner
和当文件变动会
自动reload的功能.
在此之前,请确保你已经安装了Node.js和npm.

Update: Check out an even better template option for Express
apps
.

我们从npm, the Node package manager
tool
开始。当你安装完Node.js后,你可能与此同时已经有了npm。之前曾说过Express是Node.js社区里非常稳定的,而npm是一个更加稳定的,极其少的情况下找一个项目是不依赖它的。

当你创建一个项目的时候,你会创建一个名为package.json的文件,它描述了你的项目和更多重要的易于npm安装你的项目依赖的配置。如你所料,项目使用Express会依赖Express
npm模块。

当你通过npm安装一个库,它会安装到项目里你当前所在的目录下,一个名为node_modules的文件。如果你有2个项目,且安装同样的express的时候,这并不意味着你能在不同的项目里使用它们。每个都会独立其他项目有自己的模块。Ruby和Python社区试着放到一起,因为对于早期已存在的部分,它们不会有这样的工具,而Node社区私活从这个挑战有所借鉴,面对和在最初的计划里来避免这些。?

有一种办法来安装node模块,系统范围内,不论如何都可以使用。不使用package.json,我们会通过特殊命令行来安装。现在我们要安装express,我也用下面的命令行工具:

为了做此,必须在控制台可以访问npm,然后使用下面这个命令:

npm install -g express

如果你用Mac或者Linux会得到一个权限拒绝的错误,之后需要使用sudo npm install -g express,这会提示你输入密码,继而此工具才能安装相应安装包。如果你输入了密码,当你使用-g参数的时候,你会经常不得不使用sudo的。

那么到底-g做什么呢?它会全局安装相应安装包的。如果没有使用-g,那么你会在当前所在文件夹里,你会看到新创建的名为node_modules的文件夹,它会安装在node_modules文件夹里。

I learned this the hard way when I was preparing for a flight and a few
hours of working offline. I downloaded all the tools I thought I’d need
but didn’t use -g. To this day I don’t know what folder I was in but
needless to say, I ended up just reading a book during that flight. :-)

现在我们有了全局安装的express,我们可以创建一个新的项目了。在终端里创建一个文件夹,切换到此文件夹。你可以在这个文件夹里。比如:

Mac/Linux/Windows:

mkdir ExpressProject; cd ExpressProjectressProject

现在你已经在你的新文件夹里了,我们会使用express命令来把它转成一个Express项目。

输入express -h后敲回车会看到选项列表。
如果你只是敲了express并敲了回车,你会创建一个新的全是默认配置的项目。

我使用的命令是:

1
express -s -H -c less

在使用之前,让我来告诉ä=SuperTab(‘n’)
他们都是干什么的吧:

  • -s 意思是增加sessions支持,
  • -H 意思是使用Hogan.js template library, 此库依赖于
    Mustache,
  • -c less 意思是使用Less,这个css preprocessor(预处理器)。

一个非常流行的-H配置项是使用Jade,它是默认项。所以如果你没有设置-H
-e (ejs) 或 -J
(JSHtml)
你就会默认使用Jade的。本教程里我将在我的网站上使用Hogan.js。

如果你喜欢CSS,但是希望它可以有点更强大,此时Less无疑是一个非常好的选择。如果仅仅是写普通的CSS,你只需要给它一个.less扩展名,这个应用会自动为你把它转成CSS的。

如果你不喜欢CSS,希望你的样式看起来有点想Python或者Ruby,你可能更喜欢
-c stylus选项来增加 Stylus
support//learnboost.github.io/stylus/”>Stylus
support.本教程所做的网站会使用Less或者普通的CSS。

如果你所在的当前目录不为空,此时使用express命令会引起错误的。它会询问你想如何处理,他还重写相同的所有文件的。遇到此种情况的时候你可以输入“yes”
or “no”

至此我们已经有一个express基础应用了,我们需要去安装它的依赖库。输入npm install
,并查看屏幕滚动,模块会被下载和安装。你会看到警告,可以无视。如果你看到错误,npm会停止的。

现在我们可以运行我们的测试应用,并保证它是正常可用的。输入 npm start
开始。

如果你用的是Windows,你可能会看到防火墙警告信息如下:

我建议把第一个选项选中,并点击“Allow
access”。如果不这样做的话,你无法在本地简化开发的。如果你经常在咖啡厅或者机场或者其他工作场所,或者可能使用移动设备上测试,此时的网络场景下,你需要保证第二个选项也选中。

无论你用什么样的操作系统,之后你都会看到一条消息,Express会监听3000端口。访问
http://localhost:3000/就可以看到你的应用了。需要说明的是Internet
Explorer
下你必须在最开始的地方输入http://。如果你使用IE浏览器,你也可能看到下面这个弹出框:

我会选 “Yes” ,因为我想有更多访问。我相信自己本地跑的代码。

现在你会看到基本上空的web页面上写着“Express, Welcome to Express”

现在,我们开始定制吧。别怕,很简单的!

回到终端里,按下 ctrl+C
来终止Node.js服务器。现在,使用一个代码编辑器如Sublime Text, Notepad++,
gEdit or Text
Wrangler等任意一个,打开package.json。如扩展名所示,这是一个Json文档。他看起来像Javascript。注意下面这段是控制依赖的:

1
2
3
4
5
"dependencies": {
"express": "3.2.6",
"hjs": "*",
"less-middleware": "*"
}

我们需要做的是在此处增加一些东西来让我们的app更好。尤其是我们要增加代码测试运行器和当文件变动后自动重载app的功能。

我们会在express之前增加如下行:

1
2
3
4
"mocha": "*",
"chai": "*",
"sinon": "*",
"supervisor": "*",

结果如下:

1
2
3
4
5
6
7
8
9
"dependencies": {
"mocha": "*",
"chai": "*",
"sinon": "*",
"supervisor": "*",
"express": "3.x",
"hjs": "*",
"less-middleware": "*"
}

请注意每一个都必须以逗号结束,最后一行除外。一旦你这做了,保存变更,并退出编辑器。

返回到你的终端,使用npm install来安装新的依赖。等待所有新的依赖加载完成。

我们要安装是supervisor,它是Node.js启动检查文件变动的,当他们变动了,它就会自动重载本地服务器。当你经常变动和预览结果的时候,这是非常有用的。然后如果你工作在一个需要在内存里存储信息的应用的时候,当你需要重启应用的时候,一定要注意,它也是会刷新内存的。

我们已经安装了Mocha test runner, chai assertion
library
和 the sinon mocking/stubbing
library
。它们都是帮助你测试代码的。

让我们来测试一下新功能吧。从supervisor开始。

Mac/Linux: ./node_modules/.bin/supervisor app.js

Windows: node_modules\.bin\supervisor app.js

你会再次看到的你的“Express server listening on port
3000″。在浏览器里确保它是正常运行的。

假设正常运行,让我们把它当成默认的,再次编辑你的package.json文件,注意“scripts”
部分。此时改为如下:

1
2
3
"scripts": {
"start": "node app.js"
},

之前用的命令放到引号中。注意windows用户要增加额外的\。你最终的结果应如下:

Mac/Linux:

1
2
3
"scripts": {
"start": "./node_modules/.bin/supervisor app.js"
},

Windows: (note the double \)

1
2
3
"scripts": {
"start": "node_modules\\.bin\\supervisor app.js"
},

现在保存并退出,返回到终端里,输入npm start来启动你的应用。

棒极了,让我们来做些测试吧。创建一个名为test的文件夹,并创建一个名为test.js的新文件。在你的代码编辑器里编辑此文件,增加如下代码:

1
2
3
4
5
6
7
8
var assert = require('chai').assert;
var routes = require('../routes');

suite('Routes', function() {
test("index route is defined", function() {
assert.isDefined(routes.index);
})
})

现在可以保存和关闭文件了。通过运行如下命令来测试:

Mac/Linux: ./node_modules/.bin/mocha -u tdd

Windows: node_modules\.bin\mocha -u tdd

你会看到一行绿色消息说1个通过

我们来让生活更精简一点,编辑你的package.json文件,找到“start”行并复制它。保证第一行后面有逗号哦。修改第二个配置项,从
“start” 改为
“test”,之后使用此命令来覆盖引号里的命令。你应该和下面一模一样才对:

Mac/Linux:

1
2
3
4
"scripts": {
"start": "./node_modules/.bin/supervisor app.js",
"test": "./node_modules/.bin/mocha -u tdd"
},

Windows: (note the double \)

1
2
3
4
"scripts": {
"start": "node_modules\\.bin\\supervisor app.js",
"test": "node_modules\\.bin\\mocha -u tdd"
},

现在保存并退出,让我们来使用npm test来测试吧.你会得到和之前测试一样的结果。

我们做的是创建一个test目录,并在它里面创建一个带有单一测试套件的测试文件,并且在此套件里有一个测试。

如果你喜欢的话,你可以在“watch”支持的尾部增加-w。这会导致它每一次文件变动都重跑一次测试。

简单说明一下,chai库支持3种不同的assertion框架。我更喜欢jUnit style TDD
assertions
。一些人更喜欢BDD样式的assertions,而其他人喜欢expect样式的。自己选择吧。

至此,已经没有什么可以阻挡你了。你可以编辑routes/index.js文件来给你的主页增加一些默认行为,或放置public/目录下的静态文件可直接使用。例如,你可以创建一个新的html文件保存为public/new.html,之后访问http://localhost:3000/new.html瞧瞧看吧。

不要忘记了你的测试。你可以给已有测试套件增加更多测试或创建一个附加测试套件的新文件。

更新说明:在你学习更加深入之前,请查阅even better template option for
Express
apps
.

为了便于参考,下面是我的最终版本的package.json文件。这是Windows下的例子哦:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node_modules\\.bin\\supervisor app.js",
"test": "node_modules\\.bin\\mocha -u tdd"
}
,

"dependencies": {
"mocha": "*",
"chai": "*",
"sinon": "*",
"supervisor": "*",
"express": "3.x",
"hjs": "*",
"less-middleware": "*"
}

}

Matthew Nuzum

Web guy, big thinker, loves to talk and write. Front end web, mobile and
UX developer for John Deere ISG. My projects: @dsmwebgeeks @tekrs
@squaretap ✝