-
Notifications
You must be signed in to change notification settings - Fork 25
/
tool.js
1465 lines (1368 loc) · 46.6 KB
/
tool.js
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function tool() { // 与业务没有相关性, 可以脱离业务使用的工具函数
function npm() { // npm 相关
/**
* 获取本地 package 版本号
* @param {string} name packageName
* @param {object} param1 选项
* @param {array} param1.packagePath 指定路径
*/
function getLocalVersion(name, {packagePath} = {}) { // 从本地获取版本号
const hasFile = tool().file.hasFile
const pathList = [
...require.main.paths,
`${require(`path`).parse(process.execPath).dir}/node_modules`,
`${require(`path`).parse(process.execPath).dir}/../lib/node_modules`,
]
packagePath = packagePath || pathList.find(path => hasFile(`${path}/${name}/package.json`))
if(packagePath) {
return require(`${packagePath}/${name}/package.json`).version // 从 package 中获取版本
}
}
/**
* 从 npmjs 中获取版本号
* @param {*} name packageName 名称
*/
function getServerVersion(name) { // 从 npmjs 中获取版本号
return new Promise((resolve, reject) => {
const https = require('https');
https.get(`https://registry.npmjs.org/-/package/${name}/dist-tags`, res => {
let data = ''
res.on('data', chunk => {
data += chunk
})
res.on('end', () => {
const latest = JSON.parse(data || `{}`).latest // 获取最新版本
resolve(latest)
})
}).on(`error`, (err) => {
reject(err.message)
})
})
}
/**
* 从 npmjs 检查依赖版本
* @param {*} name 要检查更新的依赖名称
* @param {object} param1 参数
* @param {string} param1.version 指定版本
* @param {array} param1.packagePath 指定路径
*/
async function checkUpdate(name, {version, packagePath} = {}) {
const getLocalVersionRes = version || getLocalVersion(name, {packagePath})
const getServerVersionRes = await getServerVersion(name).catch(err => console.log(err))
return {
local: getLocalVersionRes,
server: getServerVersionRes,
}
}
return {
getLocalVersion,
getServerVersion,
checkUpdate,
}
}
function control() { // 流程控制
/**
* 同步执行异步函数, 由于是把函数源码抽到单独的 js 文件中运行, 所以有一些限制
* - 如果依赖 babel 可能导致 toString 后的代码没有相关 polyfill
* - 入参和出参需要可序列化(json), 不会输出出参之外的其他信息
* - 函数内不要有外部依赖(例如)
* @param fn 要运行的函数
* @return {function} 接收原参数, 返回 {res, err}
*/
function asyncTosync (fn) {
const {
createNewFile,
filesCreateOrRemove,
} = file()
return (...args) => {
const { writeFileSync, readFileSync } = require(`fs`)
const fnStr = fn.toString()
const tempDir = (__dirname || require(`os`).tmpdir()).replace(/\\/g, `/`)
const fileObj = {
fnFile: createNewFile(tempDir, `fn.js`),
resFile: createNewFile(tempDir, `res.log`),
errFile: createNewFile(tempDir, `err.log`),
}
filesCreateOrRemove(fileObj, `create`)
let res = ``
let err = ``
try {
const argsString = args.map(arg => JSON.stringify(arg)).join(', ');
const codeString = `
const { writeFileSync } = require('fs')
const fn = ${fnStr}
new Promise(() => {
fn(${argsString})
.then((output = '') => {
writeFileSync("${fileObj.resFile}", String(output), 'utf8')
})
.catch((error = '') => {
writeFileSync("${fileObj.errFile}", String(error), 'utf8')
})
.finally(() => {
process.exit()
})
}
)
`
writeFileSync(fileObj.fnFile, codeString, `utf8`)
require(`child_process`).execSync(`"${process.execPath}" ${fileObj.fnFile}`)
res = readFileSync(fileObj.resFile, `utf8`)
res = res ? JSON.parse(res) : undefined
err = readFileSync(fileObj.errFile, `utf8`)
err = err ? JSON.parse(err) : undefined
} catch (error) {
console.log(`error`, error)
}
filesCreateOrRemove(fileObj, `remove`)
return {res, err}
}
}
/**
* 以 Promise 方式等待条件成立
* @param {*} condition 条件函数, 返回 true 时才陈立
* @param {*} ms 检测条件的实时间隔毫秒
* @param {*} timeout 超时
*/
function awaitTrue({
condition,
ms = 250,
timeout = 5e3,
}) {
return new Promise(async (resolve, reject) => {
let timeStart = Date.now()
let res = await condition()
while (res !== true) {
res = await condition()
if(((Date.now() - timeStart) > timeout)) { // 超时
reject(false)
}
await sleep(ms)
}
resolve(res)
})
}
/**
* 异步等待 sleep
* @param {*} ms 毫秒
*/
function sleep(ms = 1e3) { // 异步 sleep
return new Promise(resolve => setTimeout(resolve, ms))
}
return {
asyncTosync,
awaitTrue,
sleep,
}
}
function cache() { // 缓存处理程序
function delRequireCache(filePath) {
delete require.cache[require.resolve(filePath)]
}
return {
delRequireCache,
}
}
function hasPackage(name, cfg = {}) { // 是还存在某个包
const path = require(`path`)
const mainPath = cfg.mainPath || path.join(__dirname, '../') // 主程序目录
const packgePath = `${mainPath}/node_modules/${name}`
const hasPackge = tool().file.hasFile(packgePath)
return hasPackge
}
async function installPackage({cwd, env, packageName, version, attempt = 3}) {
// 注意: 修改为 npm 时某些依赖会无法安装, 需要使用 cnpm 成功率较高
// const installEr = {cnpm: `npm`}[packageName] || `cnpm`
const installEr = `cnpm`
let {MOCKM_REGISTRY, NPM_CONFIG_REGISTRY} = process.env
MOCKM_REGISTRY = MOCKM_REGISTRY || NPM_CONFIG_REGISTRY || `https://registry.npm.taobao.org/`
// --no-save 不保存依赖名称到 package.json 中
const cmd = `npx ${installEr} i ${packageName}@${version} --product --no-save --registry=${MOCKM_REGISTRY}`
console.log(`正在初始化 ${packageName}...`)
console.log(cmd)
let attemptNum = attempt // 重试次数
do {
await cli().spawn(
`npx`, cmd.split(/\s+/),
{
detached: false, // 为 true 时拥有自己的窗口, 父进程退出后继续运行
cwd,
env: {
NPM_CONFIG_REGISTRY: MOCKM_REGISTRY,
...process.env,
...env,
}
}
)
if(attemptNum < attempt) {
console.log(`重试次数 ${attempt - attemptNum}/${attempt - 1}`)
}
attemptNum = attemptNum - 1
} while (hasPackage(packageName) === false && attemptNum > 0);
const hasPackageRes = hasPackage(packageName)
console.error(`初始化 ${packageName} ${hasPackageRes ? `成功`: `失败`}`)
return hasPackageRes
}
function generate() { // 生成器
/**
* 如果某个依赖不存在, 则安装它
* @param {*} packageName 依赖名称
* @param {object} param1 配置
* @param {string} param1.version 版本, 如果不填则从 packageJson.pluginDependencies 中获取
* @param {boolean} param1.getRequire 是否安装完成后进行 require
* @param {object} param1.env 安装时的环境变量
* @param {string} param1.msg 依赖不存在时提示的消息
*/
async function initPackge(packageName, {version, getRequire = true, env = {}, msg} = {}) {
try {
const path = require(`path`)
const mainPath = path.join(__dirname, '../') // 主程序目录
const packageJson = require(`${mainPath}/package.json`)
version = version || packageJson.pluginDependencies[packageName]
const hasPackageRes = hasPackage(packageName)
if(hasPackageRes === false) { // 如果依赖不存在, 则安装它
const cnpmVersion = npm().getLocalVersion(`cnpm`)
if(cnpmVersion === undefined) { // 如果 cnpm 不存在则先安装 cnpm
await installPackage({cwd: mainPath, env, packageName: `cnpm`, version: `6.1.1` })
}
msg && console.log(msg)
await installPackage({cwd: mainPath, env, packageName, version })
}
if(getRequire) {
cache().delRequireCache(packageName)
return require(packageName)
}
} catch (err) {
console.log(`err`, err)
}
}
function nextId() { // 获取全局自增 id
global.id = (global.id || 0) + Date.now() + 1
return global.id
}
return {
initPackge,
nextId,
}
}
function hex() { // 进制转换
function string10to62(number) { // 10 进制转 62 进制, 用来压缩数字长度
const chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ'.split('')
const radix = chars.length
const arr = []
let qutient = +number
do {
const mod = qutient % radix;
qutient = (qutient - mod) / radix;
arr.unshift(chars[mod]);
} while (qutient);
return arr.join('');
}
function string62to10(str) { // 62 进制转 10 进制
str = String(str)
const chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ'
const radix = chars.length
const len = str.length
let origin_number = 0
let i = 0
while (i < len) {
origin_number += Math.pow(radix, i++) * chars.indexOf(str.charAt(len - i) || 0);
}
return origin_number;
}
return {
string10to62,
string62to10,
}
}
function cli() { // 命令行相关处理程序
/**
* 自定义控制台颜色
* https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color
* nodejs 内置颜色: https://nodejs.org/api/util.html#util_foreground_colors
*/
function colors () {
const util = require('util')
function colorize (color, text) {
const codes = util.inspect.colors[color]
return `\x1b[${codes[0]}m${text}\x1b[${codes[1]}m`
}
let returnValue = {}
Object.keys(util.inspect.colors).forEach((color) => {
returnValue[color] = (text) => colorize(color, text)
})
const colorTable = new Proxy(returnValue, {
get (obj, prop) {
// 在没有对应的具名颜色函数时, 返回空函数作为兼容处理
const res = obj[prop] ? obj[prop] : (arg => arg)
return res
}
})
// 取消下行注释, 查看所有的颜色和名字:
// Object.keys(returnValue).forEach((color) => console.log(returnValue[color](color)))
return colorTable
}
/**
* 以 Promise 方式运行 spawn
* @param {*} cmd 主程序
* @param {*} args 程序参数数组
* @param {*} opts spawn 选项
*/
function spawn (cmd, args, opts) {
opts = { stdio: `inherit`, ...opts }
opts.shell = opts.shell || process.platform === 'win32'
return new Promise((resolve, reject) => {
const cp = require('child_process')
const child = cp.spawn(cmd, args, opts)
let stdout = ''
let stderr = ''
child.stdout && child.stdout.on('data', d => { stdout += d })
child.stderr && child.stderr.on('data', d => { stderr += d })
child.on('error', reject)
child.on('close', code => {
resolve({code, stdout, stderr})
})
})
}
function parseArgv(arr) { // 解析命令行参数
return (arr || process.argv.slice(2)).reduce((acc, arg) => {
let [k, ...v] = arg.split('=')
v = v.join(`=`) // 把带有 = 的值合并为字符串
acc[k] = v === '' // 没有值时, 则表示为 true
? true
: (
/^(true|false)$/.test(v) // 转换指明的 true/false
? v === 'true'
: (
/[\d|.]+/.test(v)
? (isNaN(Number(v)) ? v : Number(v)) // 如果转换为数字失败, 则使用原始字符
: v
)
)
return acc
}, {})
}
/**
* 从 curl 命令中解析 request 库的 options 参数
* @param {string} cmd // curl/bash 命令
*/
async function getOptions(cmd) {
const curlconverter = await tool().generate.initPackge(`curlconverter`)
const requestStr = curlconverter.toNodeRequest(cmd)
let optionStr = requestStr.match(/^var request = require[\s\S].*;([\s\S]*)^function callback([\s\S]*)/m)[1] // 只取出 options 相关的代码
let options = {}
try {
const { NodeVM } = require(`vm2`)
const vm = new NodeVM()
options = vm.run(`${optionStr}\nmodule.exports = options`, `vm.js`) || ``
// 避免 node v10.12.0 出现 options.uri is a required argument
options.url = options.url || options.uri
options.uri = options.url || options.uri
} catch (err) {
console.log(`err`, err)
}
return options
}
return {
spawn,
parseArgv,
getOptions,
colors: colors(),
}
}
function url() { // url 处理程序
/**
* 根据 pathname 返回最匹配的 url
* @param {*} param0.urlList url 列表
* @param {*} param0.pathname pathname
*/
function findLikeUrl({
urlList,
pathname
}) {
const apiSplitList = new URL(`http://127.0.0.1${pathname}`).pathname.split(`/`)
const lvList = urlList.map((openApiItem) => {
const openApiSplitList = new URL(openApiItem).pathname.split(`/`)
const lv = apiSplitList.reduce((acc, apiSplitListItem, apiSplitListItemIndex) => {
return acc + (apiSplitListItem === openApiSplitList[apiSplitListItemIndex] ? 1 : 0)
}, 0)
return lv
})
function findMaxIndex(arr) { // 查找数组中最大的数的索引
const sortRes = [...arr].sort((a, b) => a - b)
return arr.findIndex((item) => item === sortRes[arr.length - 1])
}
const maxIndex = findMaxIndex(lvList)
return urlList[maxIndex]
}
function prepareProxy (proxy = {}) { // 解析 proxy 参数, proxy: string, object
const pathToRegexp = require('path-to-regexp')
const isType = type().isType
const proxyType = isType(proxy)
let resProxy = []
if(proxyType === `string`) { // 任何路径都转发到 proxy
proxy = {
'/': proxy,
}
}
function setIndexOfEnd(proxy) { // 需要排序 key:/ 到最后, 否则它生成的拦截器会被其他 key 覆盖
const indexVal = proxy[`/`]
delete proxy[`/`]
proxy[`/`] = indexVal
return proxy
}
proxy = setIndexOfEnd(proxy)
resProxy = Object.keys(proxy).map(context => {
let options = proxy[context]
const optionsType = isType(options)
if(optionsType === `string`) { // 转换字符串的 value 为对象
options = {
pathRewrite: { [`^${context}`]: options }, // 原样代理 /a 到 /a
target: options.includes(`://`) // 如果要代理的目录地址已有主域
? new URL(options).origin // 那么就代理到该主域上
: proxy[`/`], // 否则就代理到 / 设定的域上
}
}
if(optionsType === `array`) { // 是数组时, 视为设计 res body 的值, 语法为: [k, v]
const [item1, item2] = options
const item1Type = isType(item1)
const midResJson = httpClient().midResJson
const deepMergeObject = obj().deepMergeObject
if(options.length <= 1) { // 只有0个或一个项, 直接替换 res
options = {
onProxyRes (proxyRes, req, res) {
midResJson({proxyRes, res, cb: () => item1})
},
}
}
if((item1Type === `string`) && (options.length === 2)) { // 以 item1 作为 key, item2 作为 val, 修改原 res
options = {
onProxyRes (proxyRes, req, res) {
midResJson({proxyRes, res, key: item1, val: item2})
},
}
}
if((item1Type === `object`) && (options.length === 2)) { // 根据 item2 的类型, 合并 item1
options = {
onProxyRes (proxyRes, req, res) {
midResJson({proxyRes, res, cb: body => {
return ({
'deep': deepMergeObject(body, item1), // 父级【不会】被替换
'...': {...body, ...item1}, // 父级【会】被替换, 类似于js扩展运行符
})[item2 || `deep`]
}})
},
}
}
}
const re = pathToRegexp(context)
return {
re,
context,
options,
}
})
return resProxy
}
function parseProxyTarget (proxy) { // 解析 proxy 为 {pathname, origin}
let origin = ``
try {
if(typeof(proxy) === `string`) {
origin = proxy
}
if(typeof(proxy) === `object`) {
origin = proxy[`/`].target || proxy[`/`]
}
const parentUrl = new URL(origin)
const res = {
host: parentUrl.host,
port: parentUrl.port || 80,
hostname: parentUrl.hostname,
pathname: parentUrl.pathname.replace(/\/$/, '') + '/',
origin: parentUrl.origin,
isIp: (parentUrl.host.match(/\./g) || []).length === 3,
}
return res
} catch (error) {
console.error(`请正确填写 proxy 参数`, error)
process.exit()
}
}
function fullApi2Obj(api) {
let [, method, url] = api.match(/(\S+)\s+(.*)/) || [undefined, `*`, api.trim()]
if(method === `*`) {
method = `all`
}
if((url === undefined) || (url === `/`)) {
url = `/` // 注意不能是 *, 否则使用 use 时会出问题
/**
这可能与 https://github.com/expressjs/express/issues/2495 有关, 需要使用 / 或 {0,} 代替
* 和 / 不一样
假设有两个 use 中间件, 都使用了静态文件, 第一个 path 为 * , 第二个为 /test
* 的情况: /test/a.html 在第一个不存在时, 并不会进入 /test
/ 的情况: 不存在时会进入 /test
*/
}
const {path} = tool().httpClient.getClientUrlAndPath(url)
return {path, method, url}
}
/**
* 处理命令行上传入的路径参数, 如果是相对路径, 则相对于运行命令的目录, 而不是相对于书写 require() 方法文件的目录
* @param {*} pathStr 路径
*/
function handlePathArg(pathStr) {
const path = require(`path`)
let newPathStr = path.isAbsolute(pathStr) ? pathStr : `${process.cwd()}/${pathStr}` // 如果是相对路径, 则相对于运行命令的位置
newPathStr = path.normalize(newPathStr) // 转换为跨平台的路径
return newPathStr
}
function parseRegPath(rePath, url) { // 使用 path-to-regexp 转换 express 的 router, 并解析参数为对象
// 注: path-to-regexp 1.x 自带 match 方法可处理此方法, 但是当前的 json-server 依赖的 express 的路由语法仅支持 path-to-regexp@0.1.7
// 所以只能手动转换, 参考: https://github.com/ForbesLindesay/express-route-tester/blob/f39c57fa660490e74b387ed67bf8f2b50ee3c27f/index.js#L96
const pathToRegexp = require('path-to-regexp')
const keys = []
const re = pathToRegexp(rePath, keys)
const pathUrl = url
const result = re.exec(pathUrl)
const obj = keys.reduce((acc, cur, index) => {
acc[cur.name] = result[index + 1]
return acc
}, {})
return obj
}
function parseUrlArgToObjList(urlArg){ // 转换 url 参数为对象数组
const querystring = require(`querystring`)
const obj = querystring.parse(urlArg) // <= urlArg
const res = []
if(typeof(obj.action) === `string`) {
res.push(obj)
} else {
obj.action.forEach((item, index) => {
res.push({action: obj.action[index], arg: obj.arg[index]})
})
}
return res
}
return {
findLikeUrl,
prepareProxy,
parseProxyTarget,
fullApi2Obj,
handlePathArg,
parseRegPath,
parseUrlArgToObjList,
}
}
function file() { // 文件相关
/**
* 创建或删除一组文件
* @param objOrArr {object|number} 要操作的内容
* @param action {stirng} 操作方式 create remove
*/
function filesCreateOrRemove (objOrArr, action) {
const {writeFileSync, unlinkSync} = require('fs')
Object.keys(objOrArr).forEach(key => {
const name = objOrArr[key]
if (action === `create`) {
writeFileSync(name, ``, `utf8`)
}
if (action === `remove`) {
unlinkSync(name)
}
})
}
/**
* 根据 dirName 和 fileName 返回一个当前目录不存在的文件名
* @param dirName 目录
* @param fileName 名称
* @return {stirng} 例 `${dirName}/temp_${Date.now()}.${fileName}`
*/
function createNewFile (dirName, fileName) {
const newFile = `${dirName}/temp_${Date.now()}.${fileName}`
return require(`fs`).existsSync(newFile) === true ? createNewFile(dirName, fileName) : newFile
}
/**
* 检查 nodmeon 是否可以修改文件后重启应用(某些设备可以检测到修改, 但应用并没有重启)
* @param {number} timeout 多少毫秒后超时返回 false, 默认 3000
* @returns {boolean}
*/
function checkChangeRestart(timeout = 3000) {
return new Promise((resolve, reject) => {
const fs = require(`fs`)
const os = require(`os`)
const path = require(`path`)
const nodemon = require(`nodemon`)
const jsFile = path.normalize(`${os.tmpdir()}/${Date.now()}.js`)
const tag = Date.now()
const fnStr = ((arg) => {
console.log(arg)
setInterval(() => {}, 2 * 1000);
}).toString()
fs.writeFileSync(jsFile, `(${fnStr})('')`)
setTimeout(() => {
fs.writeFileSync(jsFile, `(${fnStr})(${tag})`)
}, 500);
nodemon({
ignoreRoot: [],
exec: `node ${jsFile}`,
watch: [jsFile],
stdout: false,
})
.on('readable', function(arg) {
this.stdout.on(`data`, data => {
let log =String(data).trim()
if(log && log.includes(tag)) {
end(true)
}
})
})
setTimeout(() => {
end(false)
}, timeout);
function end(isOk) {
resolve(isOk)
nodemon.emit(`quit`)
fs.existsSync(jsFile) && fs.unlinkSync(jsFile)
}
})
}
function fileStore(storePath, initValue) { // 存取需要持久化存储的数据
const fs = require(`fs`)
const {
o2s,
deepSet,
deepGet,
} = obj()
if(isFileEmpty(storePath)) {
fs.writeFileSync(storePath, o2s(initValue || {}))
} else if(initValue) { // 避免后期添加的键由于存在文件而没有正常初始化
const store = JSON.parse(fs.readFileSync(storePath, `utf-8`))
fs.writeFileSync(storePath, o2s({...initValue, ...store}))
}
let store = () => JSON.parse(fs.readFileSync(storePath, `utf-8`))
return {
set(key, val) {
const newStore = store()
deepSet(newStore, key, val)
fs.writeFileSync(storePath, o2s(newStore))
return store
},
get(key) {
const newStore = store()
return deepGet(newStore, key)
},
updateApiCount() {
const apiCountOld = this.get(`apiCount`) || 0
this.set(`apiCount`, apiCountOld + 1)
return this.get(`apiCount`)
},
}
}
function hasFile(filePath) { // 判断文件或目录是否存在
const fs = require(`fs`)
return fs.existsSync(filePath)
}
/**
* 获取文件 md5 - 同步版
* @param {*} pathOrBuffer 文件路径或 buffer
* @param {*} type 如果是文件路径时, type 为 path
* @returns
*/
function getFileMd5(pathOrBuffer, type) {
const fs = require(`fs`)
const buffer = type === `path` ? fs.readFileSync(pathOrBuffer) : pathOrBuffer
const crypto = require('crypto');
const md5 = crypto.createHash('md5').update(buffer).digest('hex')
return md5
}
/**
* 获取远程 url 的
* @param {string} url http url
* @returns {object} {data, ext} binary 和后缀名
*/
function getFile(url) {
const [, tag = ``, username, password] = url.match(/:\/\/((.+):(.+)@)/) || []
url = url.replace(tag, ``)
return new Promise((resolve, reject) => {
const http = require(url.replace(/(:\/\/.*)/, ``).trim()) // 获取 http 或 https
http.get(url, {
auth: username ? `${username}:${password}` : undefined,
}, res => {
const { statusCode } = res
if (statusCode !== 200) {
reject(statusCode)
}
let data = ''
res.setEncoding('binary')
res.on('data', (chunk) => {
data += chunk
});
res.on('end', () => {
const mime = require('mime')
const ext = mime.getExtension(res.headers[`content-type`]) || ``
resolve({
data,
ext,
})
})
}).on('error', (e) => {
reject(e.message)
});
})
}
/**
* 根据 url 获取文件的存储路径以及文件名, 避免特殊字符
* @param {string} url http 地址
* @returns {object} {pathname, fileName} fileName 是 query 参数生成的名字
*/
function getFilePath(url) {
const filenamify = require('filenamify')
const {
pathname,
search = ``,
} = new URL(url)
const fileName = filenamify(
search,
{ maxLength: 255, replacement: '_' }
)
return {
pathname,
fileName,
}
}
/**
* 备份一个 http url 对应的文件
* @param {string} baseDir 要备份于什么目录之下
* @param {string} fileUrl 文件 url
* @param {function} format 备份前格式化数据
*/
async function backUrl(baseDir = __dirname, fileUrl, format) {
let { data: fileData, ext: fileExt } = (await getFile(fileUrl).catch(err => {
console.log(err)
})) || {}
if(fileData === undefined) {
return false
}
if(fileData && format) {
fileData = format(fileData)
}
const {
pathname,
fileName,
} = getFilePath(fileUrl)
const fs = require('fs')
const dir = `${baseDir}/${pathname}`
fs.mkdirSync(dir, { recursive: true })
// 从符合备份文件名规则的所有文件中找到最新备份的那个文件名和时间, 获取文件的 md5 与请求的 md5 做比较
const getMax = fs.readdirSync(dir).reduce((acc, curFileName) => {
const re = new RegExp(`${fileName}_(\\d{4}-\\d{2}-\\d{2} \\d{2}-\\d{2}-\\d{2})\\.`)
const [, tag = ``] = curFileName.match(re) || []
const curTime = Number(tag.replace(/\D/g, ``))
return {
maxTime: acc.maxTime < curTime ? curTime : acc.maxTime,
curFileName: acc.maxTime < curTime ? curFileName : acc.curFileName,
}
}, {maxTime: 0, curFileName: ``})
const newName = time().dateFormat(`YYYY-MM-DD hh-mm-ss`, new Date())
if (getMax.maxTime) {
const oldMd5 = getFileMd5(fs.readFileSync(`${dir}/${getMax.curFileName}`))
const tempFile = `${dir}/temp`
saveFile(tempFile, fileData)
const newMd5 = getFileMd5(fs.readFileSync(tempFile))
fs.unlinkSync(tempFile)
if (oldMd5 !== newMd5) {
saveFile(`${dir}/${fileName}_${newName}.${fileExt}`, fileData)
}
} else {
saveFile(`${dir}/${fileName}_${newName}.${fileExt}`, fileData)
}
}
/**
* 获取 http url 备份文件
* @param {string} baseDir 备份于什么目录之下
* @param {string} fileUrl 文件 url
* @return {string} 最新的文件
*/
async function getBackUrl(baseDir = __dirname, fileUrl) {
const {
pathname,
fileName,
} = getFilePath(fileUrl)
const fs = require('fs')
const dir = `${baseDir}/${pathname}`
if(hasFile(dir) === false) {
return undefined
}
const getMax = fs.readdirSync(dir).reduce((acc, curFileName) => {
const re = new RegExp(`${fileName}_(\\d{4}-\\d{2}-\\d{2} \\d{2}-\\d{2}-\\d{2})\\.`)
const [, tag = ``] = curFileName.match(re) || []
const curTime = Number(tag.replace(/\D/g, ``))
return {
maxTime: acc.maxTime < curTime ? curTime : acc.maxTime,
curFileName: acc.maxTime < curTime ? curFileName : acc.curFileName,
}
}, {maxTime: 0, curFileName: ``})
if (getMax.maxTime) {
return `${dir}/${getMax.curFileName}`
} else {
return undefined
}
}
/**
* 保存文件
* @param {string} filePath 文件的路径
* @param {binary} bin 二进制内容
*/
function saveFile(filePath, bin) {
const fs = require('fs')
fs.writeFileSync(filePath, bin, { encoding: 'binary' })
}
function getMd5(path) { // 获取文件 md5
return new Promise((resolve, reject) => {
const fs = require('fs')
const crypto = require('crypto')
const md5sum = crypto.createHash('md5')
const stream = fs.createReadStream(path)
stream.on('data', (chunk) => {
md5sum.update(chunk)
})
stream.on('end', () => {
const md5 = md5sum.digest('hex').toUpperCase()
resolve(md5)
})
})
}
function getMd5Sync(path) { // 获取文件 md5
const fs = require('fs')
const buffer = fs.readFileSync(path)
return tool().string.getMd5(buffer)
}
function isFileEmpty(file) { // 判断文件是否存或为空
const fs = require(`fs`)
return (
(hasFile(file) === false)
|| fs.readFileSync(file, `utf-8`).trim() === ``
)
}
return {
filesCreateOrRemove,
createNewFile,
checkChangeRestart,
getBackUrl,
backUrl,
fileStore,
getMd5,
getMd5Sync,
isFileEmpty,
hasFile,
}
}
function middleware() { // express 中间件
const compression = require('compression') // 压缩 http 响应
function httpLog({config}) { // 设置 http 请求日志中间件
const morgan = require('morgan')
const {print} = require('./log.js')
const colors = tool().cli.colors
return morgan( (tokens, req, res) => {
const colorTable = {
1: `gray`,
2: `green`,
3: `yellowBright`,
4: `yellow`,
5: `red`,
}
const statusCode = String(res.statusCode)
const len = res.getHeader(`Content-Length`)
const str = [
tool().time.dateFormat(`hh:mm:ss`, new Date),
tool().httpClient.getClientIp(req),
res.getHeader(config.apiInHeader),
`${statusCode} ${res.statusMessage}`,
`${tokens['response-time'](req, res)} ms`,
len ? `${len} byte` : '',
].join(` `)
// 使用原生 nodejs 打印日志
print(colors[colorTable[statusCode[0]]](str)) // 根据状态码的第一位获取颜色函数
return [] // return list.join(' ')
})
}
function getJsonServerMiddlewares({config}) { // 获取 jsonServer 中的中间件
// 利用 jsonServer 已有的中间件, 而不用额外的安装
// 注意: 可能根据 jsonServer 版本的不同, 存在的中间件不同
const jsonServer = require('json-server')
const middlewares = jsonServer.defaults({bodyParser: true, logger: false, static: require(`path`).join(__dirname, '../public2')}) // 可以直接使用的所有中间件数组
middlewares.push(httpLog({config}))
const middlewaresObj = middlewares.flat().reduce((res, item) => {
// 使用 jsonServer 里面的中间件, 以保持一致:
// compression, corsMiddleware, serveStatic, logger, jsonParser, urlencodedParser
return ({
...res,
[item.name]: item,
})
}, {})
return {middlewares, middlewaresObj}
}
function reWriteRouter({app, routes = {}}) { // 根据 routes 对象, 重写路由
const rewrite = require('express-urlrewrite')
Object.keys(routes).forEach(key => {
app.use(rewrite(key, routes[key]))
})
}
function replayHistoryMiddleware ({
id,
HTTPHISTORY,
config,
business,
} = {}) {
const {
clientInjection,
historyHandle,
} = business
const {
allowCors,
setHeader,
reSetApiInHeader,
} = clientInjection({config})
const {
getHistory,
} = historyHandle({config})
return (req, res, next) => { // 修改分页参数, 符合项目中的参数
const method = req.method.toLowerCase()
const fullApi = id ? undefined :`${method} ${req.originalUrl}`
HTTPHISTORY = HTTPHISTORY || require(config._httpHistory)
const history = getHistory({history: HTTPHISTORY, id, fullApi, find: list => {
const getStatus = (item) => {
try {
return item.data.res.lineHeaders.line.statusCode