koa-program/extend/file.ts

61 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-02-10 03:40:48 +08:00
import { copyFileSync, existsSync, mkdirSync, writeFileSync } from "fs";
/**
*
* @description 便
*/
class file {
/**
*
* @description
* true
*
* @param {string} filePath
* @return {boolean}
*/
protected static createPath(filePath: string): boolean {
// 获取完整目录(去除最后一位的文件字段)
let dir = filePath.substring(0, filePath.lastIndexOf("/"));
if (dir == "" || dir == null) dir = "./"; // 不写目录名 => 根目录
// 文件夹不存在
if (!existsSync(dir)) {
let actionNotice = mkdirSync(dir, { recursive: true });
return !!actionNotice;
} else return true;
}
/**
*
* @param {string} src
* @param {string} dest
* @return {boolean}
*/
static copy(src: string, dest: string): boolean {
if (!existsSync(src)) {
console.log("源文件不存在");
return false;
}
// 复制操作
if (file.createPath(dest)) {
copyFileSync(src, dest);
return existsSync(dest);
} else return false;
}
/***
*
* @param {string} filePath
* @param data
* @return {boolean}
*/
static write(filePath: string, data: any = "") {
if (file.createPath(filePath)) {
writeFileSync(filePath, data);
return existsSync(filePath);
} else return false;
}
}
export { file };