导语:之前做了一个小项目,其中后端接口中封装了很多的方法,现在就总结罗列一下,方便保存,以便日后用到。
# 目录
- 数据库
- Node相关
- 数据处理
- 文件处理
# 数据库
- mysql连接
// mysql.js
const mysql = require('mysql');
const pool = mysql.createPool({
host: 'localhost',
port: '3306',
database: 'test',
user: 'test',
password: 'test123456.',
});
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
至于详细的方法,我已经写成一个npm包发布了,这里查看 (opens new window)。
- redis连接
// redis.js
const redis = require('redis');
const redisConfig = {
host: 'localhost',
port: 6379,
password: '123456',
options: {}
};
const redisClient = redis.createClient(redisConfig.port, redisConfig.host, redisConfig.options);
// auth
redisClient.auth(redisConfig.password);
// error
redisClient.on('error', err => {
if (err) {
console.error(err);
}
})
// connect
redisClient.on('connect', () => {
console.log('redis is connected!');
});
module.exports = redisClient;
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
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
- redis设置
function setKey(key, value, time) {
redis.set(key, JSON.stringify(value), redis.print);
redis.expire(key, time);
return true;
}
1
2
3
4
5
2
3
4
5
- redis获取
function getKey(key) {
return new Promise((resolve, reject) => {
redis.get(key, function (err, data) {
if (err) {
reject({
code: 2,
data: err
})
} else {
resolve({
code: 1,
data: JSON.parse(data)
})
}
})
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- redis限流
/**
* 限流 xxx qps/min
* @param {*} key 名称
* @param {*} max 最大次数
* @param {*} time 时间
* @returns code 1.正常 2.超出
*/
function limitAccess (key, max = 60, time = 60) {
return new Promise(async function (resolve, reject) {
let num = 1;
let limitObj = await getKey(key);
if (limitObj.code == 1 && limitObj.data == null) {
setKey(key, num, time);
} else {
num = limitObj.data+1;
setKey(key, num, time);
}
if (num > max) {
resolve({
code: 2,
})
} else {
resolve({
code: 1,
})
}
})
}
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
28
29
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
28
29
- mongodb连接
// mongo.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test',{
useNewUrlParser: true,
useUnifiedTopology: true
})
const db = mongoose.connection;
db.on('error',console.error.bind(console,'connection error:'));
db.once('open',function () {
console.log('database connect succ!')
})
module.exports = db
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
- mongodb结构
const mongoose = require('mongoose')
const MarkSchema = new mongoose.Schema({
title: String,
content: String,
author: String,
name: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Type'
},
create_time: {
type: Date,
default: Date.now
},
update_time: {
type: Date,
default: Date.now
}
})
const MarkModel = mongoose.model('Mark',MarkSchema)
module.exports = MarkModel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Node相关
- 执行命令
const process = require('child_process');
function shellExec (shell) {
return new Promise(function (resolve, reject) {
process.exec(shell, function (error, stdout, stderr) {
if (error) {
reject({
code: 1,
error,
})
} else if (stdout) {
resolve({
code: 2,
data: stdout,
})
} else {
resolve({
code: 1,
error: stderr,
})
}
})
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- 获取用户ip地址
function getClientIP(req) {
return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
req.connection.remoteAddress || // 判断 connection 的远程 IP
req.socket.remoteAddress || // 判断后端的 socket 的 IP
req.connection.socket.remoteAddress;
};
1
2
3
4
5
6
2
3
4
5
6
- 获取url信息
function getUrl (url) {
let obj = {
href: null,
pathname: null,
search: null,
query: null,
};
if (!url) {
return obj;
}
let path = url.indexOf('?') > -1 ? url.split('?') : url;
obj.href = url;
obj.pathname = typeof path == 'object' ? path[0] : path;
obj.search = typeof path == 'object' ? path[1] : null;
if (obj.search) {
let type = obj.search.indexOf('&&') > -1 ? 1 : 2;
let querys = type == 1 ? obj.search.split('&&') : obj.search.split('&');
let newQuery = {};
for (const item of querys) {
let qItem = item.split('=');
newQuery[qItem[0]] = qItem[1];
}
obj.query = newQuery;
}
return obj;
}
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
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
- 获取host
function getHost (url) {
let urllib = getUrl(url);
let addr = {
url: '',
protocal: '',
host: '',
hostname: '',
port: '',
}
let protocol = urllib.pathname.indexOf('https') === -1 ? 'http' : 'https';
let urls = urllib.pathname.split('://')[1].split('/');
let isPort = urls[0].indexOf(':') === -1;
addr.url = url;
addr.protocal = protocol;
addr.host = urls[0];
addr.port = isPort ? '' : urls[0].split(':')[1];
addr.hostname = isPort ? urls[0] : urls[0].split(':')[0];
return addr;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- 拼接参数
function getParams (url = '', data = {}, urlcode = 1) {
let result = '';
if (!url) {
return result;
}
if (Object.keys(data).length == 0) {
return result;
}
for (const key in data) {
result += `${key}=${data[key]}&`;
}
let params = result.slice(0, result.length-1);
if (urlcode == 2) {
params = escape(params);
}
result = `${url}?${params}`;
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- 获取游览器类型
function getBrowserName (req) {
let browserName = '';
let ua = req.headers['user-agent'];
let bns = ['Chrome', 'Trident', 'MSIE', 'Firefox', 'Opera', 'Safari', 'Postman'];
for(let i = 0; i< bns.length; i++) {
if (ua.indexOf(bns[i]) > -1) {
browserName = bns[i];
break;
}
};
return browserName;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
- 获取用户游览器以及设备信息
function getClientDevice(req) {
let ua = req.headers['user-agent'];
let pfs = ['Android', 'iPhone', 'iPad', 'Windows', 'Mac', 'Linux', 'Postman'];
let platform = '';
for(let i = 0; i< pfs.length; i++) {
if (ua.indexOf(pfs[i]) > -1) {
platform = pfs[i];
break;
}
};
return platform;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 数据处理
- uuid 16位
function getUuid() {
return 'xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
1
2
3
4
5
6
7
2
3
4
5
6
7
- 菜单转换
const getMenuList = function (arr) {
let newArr = [];
for (const item of arr) {
if (item.parent === 1) {
item.children = [];
newArr.push(item);
}
}
for (const itemArr of newArr) {
for (const item of arr) {
if (item.parent === itemArr.id) {
itemArr.children.push(item);
}
}
}
return newArr;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- 十进制转62进制
function str10To64(number) {
var chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ'.split(''),
radix = chars.length,
qutient = +number,
mod = '',
arr = [];
do {
mod = qutient % radix;
qutient = (qutient - mod) / radix;
arr.unshift(chars[mod]);
} while (qutient);
return arr.join('');
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
- 十进制转62进制
function str64To10(number_code) {
var chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ',
radix = chars.length,
number_code = String(number_code),
len = number_code.length,
i = 0,
origin_number = 0;
while (i < len) {
origin_number += Math.pow(radix, i++) * chars.indexOf(number_code.charAt(len - i) || 0);
}
return origin_number;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
- 10进制转16进制
function str10To16(n) {
typeof n == "string" ? n = Number(n) : ''
return n.toString(16);
}
1
2
3
4
2
3
4
- 16进制转10进制
function str16To10(n) {
return Number('0x' + n);
}
1
2
3
2
3
- 生成十六位数字
function createRandom(number = 2020061201010001001) {
const num = str10To16(number);
const serveKey = CryptoJS.enc.Utf8.parse(num);
const serveIv = CryptoJS.enc.Utf8.parse(num);
return {
key: serveKey,
iv: serveIv
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- 排序
function arrSort(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (Number(arr[i]) >= Number(arr[j])) {
let t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
return arr;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
- 二维数组转一维
const moreToOneArr = (arr) => {
let newArr = [];
for (const item of arr) {
if (item.parent === 1 && item.children.length === 0) {
newArr.push(item);
} else if (item.parent === 1 && item.children.length) {
let cList = item.children;
for (const itemA of cList) {
newArr.push(itemA);
}
newArr.push(item);
}
}
return newArr;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 文件处理
- 将base64转换为文件
function dataURLtoFile(dataurl, filename) {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1];
if (!filename) { //若无文件名则取当前时间戳
filename = Date.parse(new Date()) + '.jpg';
}
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {
type: mime
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- base64转化为blob
function dataURItoBlob(base64Data) {
var byteString;
if (base64Data.split(',')[0].indexOf('base64') >= 0)
byteString = atob(base64Data.split(',')[1]);
else {
byteString = unescape(base64Data.split(',')[1]);
}
var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ia], {
type: mimeString
});
return blob;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- 重命名文件
function renameFile (oldPath, newPath) {
return new Promise((resolve, reject) => {
fs.rename(oldPath, newPath, function (err) {
if (err) {
reject({
code: 101,
err
});
} else {
resolve({
code: 200
})
}
});
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- 写入文件
function writeIcoFile (oldPath, newPath) {
return new Promise((resolve, reject) => {
fs.readFile(oldPath, function (err, data) {
if (err) {
reject({
code: 101,
err
});
} else {
fs.writeFile(newPath, data, function (err) {
if (err) {
reject({
code: 101,
err
});
} else {
resolve({
code: 200
})
}
});
}
})
})
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
- 读取文件夹下图片列表
function readDirList (dirPath) {
return new Promise((resolve, reject) => {
fs.readdir(dirPath, {encoding: 'utf8'}, function (error, files) {
if (error) {
reject({
code: 101,
error
});
} else {
resolve({
code: 200,
data: files,
})
}
})
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 写在最后
以上就是我在项目开发中常用到的一些方法,现在做一个总结归纳,后面还会陆续补充更多更好用的方法。