@cloudroom/load-static
Version:
download
64 lines (54 loc) • 1.89 kB
JavaScript
const download = require('download');
const fs = require('fs');
const compressing = require('compressing');
const path = require('path')
const cwd = path.resolve(__dirname)
const downloadStatic = async (url, config = {}) => {
console.log('download url:', url);
let metadata = {};
const { filename, dir = cwd, needCompress = false } = config;
try {
metadata = require('./cache/metadata.json');
} catch (err) {
}
if (!metadata[url]) {
const str = Math.random().toString(36).slice(2);
await download(url, path.resolve(__dirname, 'cache'), {
filename: str,
})
metadata[url] = {
filename: str
}
fs.writeFileSync(path.resolve(__dirname, './cache/metadata.json'), JSON.stringify(metadata));
}
if (needCompress) {
try {
fs.rmSync(dir, { recursive: true });
} catch (error) {
}
await compressing.zip.uncompress(path.resolve(__dirname, './cache/' + metadata[url].filename), dir)
} else {
// 递归创建目录
function ensureDirExists(dirPath) {
if (!fs.existsSync(dirPath)) {
const parentDir = path.dirname(dirPath);
if (parentDir !== '.' && parentDir !== '/' && !fs.existsSync(parentDir)) {
ensureDirExists(parentDir); // 递归调用以确保父目录存在
}
fs.mkdirSync(dirPath);
}
}
// 确保目录存在
ensureDirExists(dir);
fs.copyFileSync('./cache/' + metadata[url].filename, dir + filename);
}
}
/* downloadStatic(
`http://127.0.0.1:8080/x86_64.zip`,
{
filename: '123.zip',
dir: './unzip/',
needCompress: true
}
) */
module.exports = downloadStatic;