75 lines
2.2 KiB
JavaScript
75 lines
2.2 KiB
JavaScript
const fs = require('fs')
|
|
const path = require('path')
|
|
|
|
// console adapter.
|
|
global.logger = global.logger || {};
|
|
logger.log = (Editor && Editor.log) || console.log;
|
|
logger.info = (Editor && Editor.info) || console.info;
|
|
logger.warn = (Editor && Editor.warn) || console.warn;
|
|
logger.error = (Editor && Editor.error) || console.error;
|
|
logger.success = (Editor && Editor.success) || (Editor && Editor.info) || console.log;
|
|
|
|
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) {
|
|
const st = fs.statSync(src);
|
|
if (st.isFile()) {
|
|
var readable = fs.createReadStream(src);//创建读取流
|
|
var writable = fs.createWriteStream(dst);//创建写入流
|
|
readable.pipe(writable);
|
|
return;
|
|
} else if (!st.isDirectory()) {
|
|
return;
|
|
}
|
|
if (!fs.existsSync(dst)) {
|
|
fs.mkdirSync(dst, {recursive: true});
|
|
}
|
|
//读取目录
|
|
const paths = fs.readdirSync(src);
|
|
for (let path of paths) {
|
|
this.copy(src + '/' + path, dst + '/' + path);
|
|
}
|
|
};
|
|
|
|
write(filePath, content) {
|
|
const pathInfo = path.parse(filePath);
|
|
// console.log('写文件:', filePath, pathInfo.dir)
|
|
if (!fs.existsSync(pathInfo.dir)) {
|
|
fs.mkdirSync(pathInfo.dir, {recursive: true});
|
|
}
|
|
fs.writeFileSync(filePath, content, 'utf-8');
|
|
}
|
|
}
|
|
|
|
module.exports = new FileUtil(); |