先说明常用的模块:
1.crypto 用来做md5加密:
var md5 = crypto.createHash('md5'),
md5password = md5.update(password).digest('hex');
2.formidable 文件上传:
router.post('/',function(req,res){
var form = new formidable.IncomingForm();
//设置编辑
form.encoding = 'utf-8';
form.uploadDir = 'public'+AVATAR_UPLOAD_FOLDER;
//保留后缀
form.keepExtensions = true;
//文件大小 2m
form.maxFieldsSize = 2 * 1024 * 1024;
//上传文件的入口文件
form.parse(req, function(err, fields, files) {
if (err) {
res.locals.error = err;
res.render('index', { title: TITLE });
return;
}
var extName = ''; //后缀名
switch (files.fulAvatar.type) {
case 'image/pjpeg':
extName = 'jpg';
break;
case 'image/jpeg':
extName = 'jpg';
break;
case 'image/png':
extName = 'png';
break;
case 'image/x-png':
extName = 'png';
break;
}
if(extName.length == 0){
res.locals.error = '只支持png和jpg格式图片';
res.render('index', { title: TITLE });
return;
}
var avatarName = Math.random() + '.' + extName;
var newPath = form.uploadDir + avatarName;
fs.renameSync(files.fulAvatar.path, newPath); //重命名
var imgs = AVATAR_UPLOAD_FOLDER + avatarName;
IMGS_ARRAY.push(imgs);
});
//res.locals.success = '上传成功';
res.redirect('/details');
/* res.render('details',{ title:'图片列表', imgs:IMGS_ARRAY });*/
});
3.press-session session控制
connect-mongo 是用来将connect的session持久化到mongodb中的
常见用法:
app.use(session({ key: 'session', secret: 'keboard cat', cookie:{maxAge: 1000*60*60*24},
store: new MongoStore({ db: 'notes', mongooseConnection: mongoose.connection }),
resave: false,
saveUninitialized: true
}));
4.前端框架代码管理使用bower, 常常用bootstraps 的css
$ npm install -g bower //
bower install bootstrap
安装bootstrap时有可能会出现这种问题:
bower ENOGIT git is not installed or not in the PATH
那是因为没有安装git,可以在windows的git bash下操作,或者linux安装git
在 project 目录 下安装完bootstrap后在目录下会出现 bower_components 目录,但是在ejs文件中直接引用会出现 css找不到
<link rel="stylesheet" type="text/css" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/stylesheets/style.css" />
<script src="/bower_components/jquery/dist/jquery.min.js" type="text/javascript">script>
需要在 project 的plublic目录下 执行 bower install bootstrap;结构如下:
5.在app.js中添加路由和错误处理时需要注意:
添加的所有get,post路由必须在 错误处理前,否则 不能先执行路由:
6.数据库连接模块:
var mongoose = require(‘mongoose’);
var db = mongoose.connect(‘mongodb://localhost/notes‘); //数据库连接
//定义model中的schema
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var userSchema = new schema({
username: String,
password: String,
email: String,
createTime:{
type:Date,
default: Date.now
}
});
//User对应着数据库中的 collections
exports.User = mongoose.model('User', userSchema);
//或者module.exports = mongoose.model('User', userSchema);
完整的nodeJs实现的nodeJs比较示例代码:
http://download.csdn.net/detail/hahayikeshu/9575262