worker.js
3.1 KB
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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const path = require('path');
require('../../config/index');
const job_handlers = new Map();
function loadAllJSFiles(dirPaths, options = {}) {
const { ignoreNodeModules = true, filter = null } = options;
const loadedModules = {};
if (!Array.isArray(dirPaths)) {
dirPaths = [dirPaths];
}
dirPaths.forEach(dirPath => {
const absoluteDir = path.resolve(dirPath);
function scanDirectory(currentDir, relativePath = '') {
const files = fs.readdirSync(currentDir);
files.forEach(file => {
const fullPath = path.join(currentDir, file);
const stat = fs.statSync(fullPath);
const newRelativePath = path.join(relativePath, file);
if (stat.isDirectory()) {
if (ignoreNodeModules && file === 'node_modules') {
return;
}
scanDirectory(fullPath, newRelativePath);
}
else if (path.extname(file) === '.js' &&
(!filter ||
(typeof filter === 'function' && filter(fullPath)) ||
(filter instanceof RegExp && filter.test(fullPath)))) {
try {
const module = require(fullPath);
const moduleKey = newRelativePath.replace(/\.js$/, '');
loadedModules[moduleKey] = module;
}
catch (err) {
console.error(`加载模块失败: ${fullPath}`, err);
}
}
});
}
scanDirectory(absoluteDir);
});
return loadedModules;
}
function wrapper_task(func) {
return async function (...args) {
try {
return await func(...args);
}
catch (error) {
return { error };
}
};
}
(() => {
const modules = loadAllJSFiles(['./build/job'], {
ignoreNodeModules: true,
filter: (filePath) => !['build/job/index.js', 'build/job/worker.js'].find(item => filePath.includes(item))
});
console.log(`=============开始加载任务=============`);
for (const key1 in modules) {
var m = modules[key1];
for (const key2 in m) {
if (typeof m[key2] === 'function') {
if (job_handlers.has(key2)) {
console.log(key2 + '已存在');
continue;
}
job_handlers.set(key2, wrapper_task(m[key2]));
}
}
}
console.log(`=============任务加载完毕 共${job_handlers.size}个=============`);
})();
module.exports = ({ name, args }) => {
switch (name) {
case 'get_task_list':
return job_handlers;
case 'get_task_keys':
return Array.from(job_handlers.keys());
default:
break;
}
var func = job_handlers.get(name);
if (!func) {
throw new Error(`任务${name}不存在`);
}
return func(args);
};
//# sourceMappingURL=worker.js.map