wangzhibo
6 天以前 7bd866831780abcf5a59c4cbb7d1be456eea7c99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import fs from "fs";
import { join } from "path";
import { config } from "../config";
import prettier from "prettier";
 
// 根目录
export function rootDir(path: string) {
    switch (config.type) {
        case "app":
            return join(process.env.UNI_INPUT_DIR!, path);
 
        default:
            return join(process.cwd(), path);
    }
}
 
// 首字母大写
export function firstUpperCase(value: string): string {
    return value.replace(/\b(\w)(\w*)/g, function ($0, $1, $2) {
        return $1.toUpperCase() + $2;
    });
}
 
// 横杠转驼峰
export function toCamel(str: string): string {
    return str.replace(/([^-])(?:-+([^-]))/g, function ($0, $1, $2) {
        return $1 + $2.toUpperCase();
    });
}
 
// 创建目录
export function createDir(path: string, recursive?: boolean) {
    try {
        if (!fs.existsSync(path)) fs.mkdirSync(path, { recursive });
    } catch (err) {}
}
 
// 读取文件
export function readFile(path: string, json?: boolean) {
    try {
        const content = fs.readFileSync(path, "utf8");
        return json
            ? JSON.parse(content.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, ""))
            : content;
    } catch (err) {}
 
    return "";
}
 
// 写入文件
export function writeFile(path: string, data: any) {
    try {
        return fs.writeFileSync(path, data);
    } catch (err) {}
 
    return "";
}
 
// 解析body
export function parseJson(req: any): Promise<any> {
    return new Promise((resolve) => {
        let d = "";
        req.on("data", function (chunk: any) {
            d += chunk;
        });
        req.on("end", function () {
            try {
                resolve(JSON.parse(d));
            } catch {
                resolve({});
            }
        });
    });
}
 
// 格式化内容
export function formatContent(content: string, options?: prettier.Options) {
    return prettier.format(content, {
        parser: "typescript",
        useTabs: true,
        tabWidth: 4,
        endOfLine: "lf",
        semi: true,
        ...options,
    });
}
 
export function error(message: string) {
    console.log("\x1B[31m%s\x1B[0m", message);
}
 
export function success(message: string) {
    console.log("\x1B[32m%s\x1B[0m", message);
}