一、简述
本篇博客用来记录初次浏览Node.js、Express的代码时,遇到的函数接口和模块。根据遇到先后顺序并且是感兴趣的,随即记录下。因此本篇博客比较杂乱。
Node.js官网手册:https://nodejs.org/zh-cn/docs/
Express官网手册:https://www.expressjs.com.cn/4x/api.html
二、函数
1、require:加载模块或文件
无路径(也称为加载模块):require('find')
有路径(也称为加载文件):require('./find.js')
三、内置模块
1、path:路径、文件相关操作接口
例如:
path.basename(path[, suffix]):从路径中获取文件名
path.delimiter:多个路径的界定符,如linux常同‘:’,windows常用‘;’
path.dirname(path):从路径中获取目录名
path.extname(path):获取后缀
path.join([...paths]):将多个字符串paths合并成一个路径
2、fs:文件操作接口
Node.js 文件系统(fs 模块)模块中的方法均有异步和同步版本,例如读取文件内容的函数有异步的 fs.readFile() 和同步的 fs.readFileSync()。异步的方法函数最后一个参数为回调函数,回调函数的第一个参数包含了错误信息(error)。
建议使用异步方法,比起同步,异步方法性能更高,速度更快,而且没有阻塞。
var fs = require("fs");
// 异步读取
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("异步读取: " + data.toString());
});
// 同步读取
var data = fs.readFileSync('input.txt');
console.log("同步读取: " + data.toString());
其他操作
打开文件:fs.open(path, flags[, mode], callback)
获取文件信息:fs.stat(path, callback)
写入文件:fs.writeFile(file, data[, options], callback)
读取文件:fs.read(fd, buffer, offset, length, position, callback)
关闭文件:fs.close(fd, callback)
截取文件:fs.ftruncate(fd, len, callback)
删除文件:fs.unlink(path, callback)
创建目录:fs.mkdir(path[, options], callback)
读取目录:fs.readdir(path, callback)
删除目录:fs.rmdir(path, callback)
四、第三方模块
1、http-errors:错误处理中间件。
var createError = require('http-errors');
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
2、express:Web 开发框架
1)app.set(name, value):类似设置键值对,例如:
app.set('title', 'My Site')
app.get('title') // "My Site"
设置模板
app.set('views', __dirname + '/views');//设置模板文件夹,__dirname是node.js里面的全局变量,即取得执行的js所在的路径
app.set('view engine', 'jade');//设置模板引擎
模板引擎除了Jade之外,express.js还支持EJS(embedded javascript)、Haml、CoffeScript和jQuerytemplate等js模板
2)app.use([path,] callback [, callback…]):用于中间件的调用
将指定的一个或多个中间件函数安装在指定的路径上:当请求的路径的基与路径匹配时,将执行中间件函数。
3)app.METHOD:路由方法的调用,例如GET、PUT、POST等,对应的方法为 app.get(), app.post(), app.put()
3、cookie-parser:cookie解析中间件
最简单的使用就是cookie的设置与解析,cookie的设置使用res.cookie方法,cookie的解析使用cookie-parser中间件
cookie-parser中间件需要导入,不能直接使用
// 导入express
const express=require('express')
// 导入cookie中间件
const cookieParser = require('cookie-parser');
const app = express();
// 使用cookie-parser解析客户端传入的cookie 加密解密
app.use(cookieParser());
// 向客户端发送cookie
app.get('/send',(req,res)=>{
res.cookie('name','nihao',{maxAge:60*1000})
res.send('向客户端发送cookie')
})
app.listen( 3000,()=>{
console.log(`serve running at http://localhost:3000`)
})
4、morgan:记录日志中间件
NodeJs中Express框架使用morgan中间件记录日志。
将信息打印到控制台:
var logger = require('morgan');
app.use(logger('dev'));
将信息打印到文件中
var logger = require('morgan');
const fs=require('fs');
const logFileName = path.join(__dirname, 'log', 'access.log');
const writeStream = fs.createWriteStream(logFileName, {
flags: 'a' //追加
});
app.use(logger('combined', {
stream: writeStream
}));
5、rootpath:获取项目的跟目录
为了解决各个模块引用时,需要记录模块之间的相对路径的问题。使用rootpath后,所有模块都是相对于项目根目录。
1)安装
npm install rootpath
2)使用
使用方法:一般在文件开头,使用require调用其它模块之前先使用它
require('rootpath')();
下面示例展示使用前后的对比,假定该js文件在目录“$HOME_PROJECT/lib/math/”中
使用之前:
// 该文件在$HOME_PROJECT/lib/math中,“..”表示返回到$HOME_PROJECT/lib/目录
// 即使用其它的库'../myLibrary'表示:$HOME_PROJECT/lib/myLibrary
var myLib = require('../myLibrary');
var myUtils = require('../../utils/myUtils');
var myTest = require('../../test/myTest');
使用之后:
require('rootpath')();
// 使用rootpath后,所有的require都是相对于$HOME_PROJECT目录开始,不需要记录模块之间的相对路径
var myLib = require('lib/myLibrary');
var myUtils = require('utils/myUtils');
var myTest = require('test/myTest');
6、dotenv:加载配置变量到程序中
Dotenv 是一个零依赖的模块,它能将配置变量从 .env 文件加载到 process.env 中。
使用方法:
1)安装
npm install dotenv
2)创建.env文件
在根目录下创建==.env==文件,注意env前面有‘点’,写入如下内容:
HOST=localhost
PORT=3000
3)在js中使用变量
require('dotenv').config({ path: '.env' })
console.log(process.env.HOST) // localhost
console.log(process.env.PORT) // 3000
7、cors:跨域资源共享
CORS(Cross-Origin Resource Sharing):跨域资源共享,简称“跨域”,是一种基于 HTTP Header 的机制,该机制通过允许服务器标示除了它自己以外的其它 origin(域,协议和端口),这样浏览器可以访问加载这些资源。
当协议、子域名、主域名、端口号中任意一个不相同时,都算作不同域,不同域之间相互请求资源,就算作“跨域”。
参见博客:详解HTTP跨域
1)安装
npm install cors
2)简单使用
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
3)指定路由的CORS
var express = require('express')
var cors = require('cors')
var app = express()
app.get('/products/:id', cors(), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for a Single Route'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
4)配置CORS
var express = require('express')
var cors = require('cors')
var app = express()
var corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for only example.com.'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
8、body-parser:解析Node.js正文(主体)内容的中间件
1)简述
支持四种解析器
JSON body parser
Raw body parser
Text body parser
URL-encoded form body parser
2)最简单的示例
示例演示:添加一个通用JSON和url编码的解析器作为顶级中间件,它将解析所有传入请求的主体。这是最简单的设置。
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
3)推荐用法
将特定的体解析器添加到需要它们的路由。
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
res.send('welcome, ' + req.body.username)
})
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
// create user in req.body
})
4)更改解析器接受的类型
所有解析器都接受一个类型选项,该选项允许您更改中间件将要解析的Content-Type。
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }))
9、http/https:搭建http/https服务器
示例展示
// curl -k https://localhost:8000/
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);