Node.js部分框架知识点整理

使用Express框架及周边的一些框架碰到了一系列的问题,把解决方法整理记录一下。

解决multer无法识别ng-file-upload批量上传文件

Multer not accepting files in array format gives ‘Unexpected Filed Error’

ng-file-upload上传插件批量上传文件时默认使用files[0], files[1], files[2]…这样的数组形式标识上传文件,而multer无法识别同样名字的上传文件。因此需要在ng-file-upload的配置中修改arrayKey属性:

1
2
3
4
5
6
7
Upload.upload({
url: '/upload',
arrayKey: '', // default is '[i]'
data: {
files: files
}
})


Express中替换模板为HTML

Why is express telling me that my default view engine is not defined?

Express4中的默认模板为Jade,如果要替换为html则需要引入ejs模板再指定模板文件:

1
2
3
var ejs = require('ejs');
app.set('view engine', 'html');
app.engine('html', ejs.renderFile);


Mongoose 部分知识点

加密字段

Mongoose password hashing
Mongoose - validate email syntax

存储如用户密码相关字段时,需要对数据进行加密,这里使用最简单的md5加密方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var UserSchema = new Schema({
email: { type: String, trim: true, required: true, unique: true},
password: { type: String, required: true, set: hashPassword }
});
function hashPassword(password){
var md5 = crypto.createHash('md5');
md5.update(password);
return md5.digest('hex');
}

//验证密码
UserSchema.methods.comparePassword = function(candidatePassword){
return this.password === hashPassword(candidatePassword);
};
//验证邮箱
UserSchema.path('email').validate(function (email) {
var emailRegex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return emailRegex.test(email);
}, 'Invalid email address');


关联ID

unable to use $match operator for mongodb/mongoose aggregation with ObjectId

虽然mongodbnosql类型的数据库,如果想类似与sql类型的数据库对两张表进行关联的话可以使用内置的ObjectId字段关联,在建立表关联的时候需要将字段设置成mongoose.Schema.Types.ObjectId类型,进行$match查询时需要转换为mongoose.Types.ObjectId类型,如:

1
2
3
4
5
6
7
8
9
var UserSchema = new Schema({
email: { type: String, trim: true, required: true, unique: true},
password: { type: String, required: true, set: hashPassword },
bills: [{ type: Schema.Types.ObjectId, ref: 'Bill' }]
});

//select
$matchObject['host'] = mongoose.Types.ObjectId(hostId);
var condition = [{ $match: $matchObject }];


转换时区

Mongodb aggregate timezone 问题

Mongodb默认存入的时间为UTC时间,因此进行聚合操作的时候需要对时间进行时区转换:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var timeOffset = () => {
//The getTimezoneOffset() method returns the time difference between UTC time and local time, in minutes.
var offset = new Date().getTimezoneOffset();
offset = -offset * 60 * 1000;
return offset;
};

$group: {
'_id': {
'year': { $year: { $add: ['$costDate', utils.timeOffset] } },
'month': { $month: { $add: ['$costDate', utils.timeOffset] } },
'day': { $dayOfMonth: { $add: ['$costDate', utils.timeOffset] } }
}
}


NodeJs网页爬虫

request/request
cheeriojs/cheerio
NodeJs妹子图爬虫
通读cheerio API

网页爬虫需要用到两个模块:requestcheeriorequest用来请求网页,cheerio用来解析网页。
cheerio的方法与效果跟jQuery的方法类似

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
26
27
var request = require('request');
var cheerio = require('cheerio');

var url = 'http://www.gamersky.com/';
request(url, function(error, response, body){
if (!error && response.statusCode == 200) {
//请求网址返回的页面
//console.log(body);
//通过cheerio解析返回的网页
var $ = cheerio.load(body);
//获取新闻列表
var news = [];
//循环遍历新闻列表
$('li.li3').each(function(i, elem){
//获取列表里面的div
var $div = $('div.txt', elem);
var link = {};
//装载标题
link['title'] = $('a', $div).text();
//装载链接
link['link'] = $('a', $div).attr('href');
//放入到新闻列表中
news.push(link);
});
console.log(news);
}
});