node 核心模块
- 文件操作fs
- http 服务
- url 路径操作模块
- path 路径处理模块
- os 操作系统信息
路径操作模块
path.basename('c:/a/b/c/index.js') // index.js (文件名)
path.dirname('c:/a/b/c/index.js') // c:a/b/c (目录)
path.extname('c:/a/b/c/index.js') // .js (扩展名)
path.isAbsolute('c:/a/b/c/index.js') // 是否是绝对路径
path.parse('c:/a/b/c/index.js') // 整合以上
<!-- {
root: 'c:/',
dir: 'c:/a/b/c',
base: 'index.js',
ext: '.js',
name: 'index'
}-->
path.join(__dirname, './static') // ☆ (路径拼接用)join 会处理相应的斜杆,避免出错
path.join('c:/a', b) // c:\\a\\b
复制代码
- __dirname 可以用来获取当前文件模块所属目录的绝对路径(动态获取)
- __filename 可以用来获取当前文件的绝对路径(动态获取)算上文件名
node 环境中的相对路径是相对node的执行命令所处的路径。所以在文件操作中需要将相对的路径统一都转换为 动态的绝对路径 ☆
注意: require('./b') 这个路径就是相对当前文件环境,和执行路径无关
node 对请求状态码的设置
res.status(200).json({})
res.status(500).json({
success: true,
err_code: '500'
message: ''
})
复制代码
mongoose 第三方包操作MongoDB
var mongoose = require('mongoose')
mongoose.connect('mongodb://', {useMongoClient: true})
// 设计模型
// 约束的目的是为了保证数据的完整性,不要有脏数据。
// 有时会把数据提出
// ====================
var userSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
})
mongoose.model('xxname', userSchema)
// ====================
var Cat = mongoose.model('cat', {name: String});
// 实例化一个cat
var kitty = new Cat({name: 'Zildjian'});
// 持久化保存kitty 实例
kitty.save(function(err){
if(err){
console.log(err)
}else{
}
})
复制代码
mongoose 增删改查
-
增
- save
-
删
- remove
-
改
- findByIdAndUpdate
-
查
- find findOne
mongoose 结合async await 的使用
router.post('./register', async function(req, res){
var body = req.body
try{
if(await User.findOne({email: body.email})){
return res.status(200).json({
err_code: 1,
message: '邮箱已存在'
})
}
if(await User.findOne({nickname: body.nickname}){
return res.status(200).json({
err_code: 2,
message: '昵称已存在'
})
}
body.password = md5(md5(body.password))
// 创建用户,执行注册
await new User(body).save()
}catch(err){
res.status(500).json({
err_code: 500,
message: err.message
})
}
})
复制代码
301 永久重定向(浏览器会缓存重定向的地址)
302 临时重定向 (浏览器不会缓存,每次都会重新请求)
nodejs 调用系统命令,日子乱码
原因:简体中文windows命令行,都使用的是CP936(近似于gb2312)编码,nodejs以utf8识别是会出问题。 临时办法:先用binary来存储输出的文本,再用iconv来以cp936解析。 其他需要安装 iconv-lite 的依赖
var child_process = require('child_process');
var iconv = require('iconv-lite');
var encoding = 'cp936';
var binaryEncoding = 'binary';
child_process.exec('svn log', { encoding: binaryEncoding }, function(err, stdout, stderr){
console.log(iconv.decode(new Buffer(stdout, binaryEncoding), encoding), iconv.decode(new Buffer(stderr, binaryEncoding), encoding));
});
复制代码