hot-update/packages/update-manager/js/FileUtils.js

65 lines
1.7 KiB
JavaScript
Raw Normal View History

2021-02-01 16:11:00 +00:00
const fs = require('fs')
const path = require('path')
class FileUtil {
/*
* 获取window上的文件目录以及文件列表信息
* @param { String } localDir 本地路径
* @return { files, dirs }
* */
listDirsAndFiles(localDir) {
const dirs = []
const files = []
const dir = fs.readdirSync(localDir)
for (let i = 0; i < dir.length; i++) {
const p = path.join(localDir, dir[i])
const stat = fs.statSync(p)
if (stat.isDirectory()) {
dirs.push(p)
const children = this.listDirsAndFiles(p)
dirs.push(...children.dirs)
files.push(...children.files)
} else {
files.push(p)
}
}
return {
files,
dirs
}
}
/**
* 拷贝文件或目录
* @param src
* @param dst
*/
copy(src, dst) {
2021-02-01 16:11:00 +00:00
const st = fs.statSync(src);
if (st.isFile()) {
const data = fs.readFileSync(src);
fs.writeFileSync(dst, data);
2021-02-01 16:11:00 +00:00
return;
}
2021-02-01 16:11:00 +00:00
if (!fs.existsSync(dst)) {
fs.mkdirSync(dst, {recursive: true});
}
2021-02-01 16:11:00 +00:00
//读取目录
const files = fs.readdirSync(src);
for (let p of files) {
this.copy(src + path.sep + p, dst + path.sep + p);
2021-02-01 16:11:00 +00:00
}
};
write(filePath, content) {
const pathInfo = path.parse(filePath);
if (!fs.existsSync(pathInfo.dir)) {
fs.mkdirSync(pathInfo.dir, {recursive: true});
}
fs.writeFileSync(filePath, content, 'utf-8');
}
}
module.exports = new FileUtil();