# 工具方法
# 串行执行异步任务
const serialExecute = async (tasks = []) => {
const resultList = [];
for (task of tasks) {
try {
resultList.push(await task());
} catch (e) {
resultList.push(null);
}
}
return resultList;
};
# 并行执行异步任务
const concurrentExecute = async (tasks = []) => {
const resultList = await Promise.all(tasks.map((task) => task()));
return resultList;
};
# 延迟函数
function sleep(time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, time);
});
}
# 生成随机字符串
function randomString(length) {
// 不能输入 %&\
// 可以输出 /!@#$^*()_+|?
let chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
let result = "";
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
# 打乱数组
function shuffle(arr) {
let len = arr.length;
while (len) {
let idx = parseInt(Math.random() * len);
[arr[len - 1], arr[idx]] = [arr[idx], arr[len - 1]];
len--;
}
return arr;
}
# 追加零
function pad(num) {
// 0 0
// 1 001
if (num == 0) return 0;
if (num < 10) return "00" + num;
if (num < 100) return "0" + num;
return num;
}
# 创建目录
function mkdir(dir) {
fs.mkdir(dir, function (err) {
if (!err) {
console.log(green("创建目录: "), dir);
}
});
}
# 下载图片
const downloadImg = async (src, dir) => {
console.log(dir);
if (/^data:(.+?);base64,(.+)$/.test(src)) {
await base64ToImg(src, dir);
} else {
await urlToImg(src, dir);
}
};
const urlToImg = (url, file) => {
const mod = /^https:/.test(url) ? https : http;
const dir = path.dirname(file);
fs.mkdir(dir, function (err) {
if (!err) {
console.log("成功创建" + dir + "目录");
}
});
mod.get(url, (res) => {
res.pipe(fs.createWriteStream(file)).on("finish", () => {
console.log(file + "下载成功");
});
});
};
const base64ToImg = async function (base64Str, file) {
try {
const matches = base64Str.match(/^data:(.+?);base64,(.+)$/);
const dir = path.dirname(file);
fs.mkdir(dir, function (err) {
if (!err) {
console.log("成功创建" + dir + "目录");
}
});
const content = matches[2];
await fs.writeFile(file, content, "base64");
console.log(file + " 下载成功");
} catch (e) {
console.log(e);
}
};
# 获取主机网络地址
const os = require("os");
function getNetworkIp() {
let hosts = []; // 打开的host
try {
// 获得网络接口列表
let network = os.networkInterfaces();
for (let dev in network) {
let iface = network[dev];
for (let i = 0; i < iface.length; i++) {
let alias = iface[i];
if (alias.family === "IPv4" && alias.address !== "127.0.0.1") {
hosts.push(alias.address);
}
}
}
} catch (e) {
hosts.push("localhost");
}
return hosts;
}
# 获取 UserAgent
async function getPuppeteerChromeUA() {
const browser = await puppeteer.launch();
const ua = await browser.userAgent();
await browser.close();
return ua;
}