ph-utils 0.6.1 → 0.6.2
Sign up to get free protection for your applications and to get access to all the features.
- package/lib/file.js +19 -19
- package/package.json +1 -1
package/lib/file.js
CHANGED
@@ -12,19 +12,19 @@ import fs from "node:fs/promises";
|
|
12
12
|
* @returns 文件内容
|
13
13
|
*/
|
14
14
|
export async function read(filepath, defaultValue) {
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
}
|
15
|
+
let content;
|
16
|
+
try {
|
17
|
+
content = await fs.readFile(filepath, "utf8");
|
18
|
+
if (defaultValue != null && typeof defaultValue === "object") {
|
19
|
+
return JSON.parse(content);
|
21
20
|
}
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
return defaultValue;
|
21
|
+
return content;
|
22
|
+
} catch (error) {
|
23
|
+
if (defaultValue === undefined) {
|
24
|
+
throw error;
|
27
25
|
}
|
26
|
+
return defaultValue;
|
27
|
+
}
|
28
28
|
}
|
29
29
|
/**
|
30
30
|
* 写入 JSON 格式的数据到文件
|
@@ -35,12 +35,12 @@ export async function read(filepath, defaultValue) {
|
|
35
35
|
* @property opts.format 是否在写入 json 数据时,将 JSON 数据格式化2个空格写入, 默认为 true
|
36
36
|
*/
|
37
37
|
export async function write(file, data, opts) {
|
38
|
-
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
|
43
|
-
|
38
|
+
let writeData = data.toString();
|
39
|
+
opts = { json: true, format: true, ...opts };
|
40
|
+
if (opts.json === true && typeof data === "object") {
|
41
|
+
writeData = JSON.stringify(data, null, opts.format === true ? 2 : 0);
|
42
|
+
}
|
43
|
+
return await fs.writeFile(path.resolve(file), writeData);
|
44
44
|
}
|
45
45
|
/**
|
46
46
|
* 根据文件的 stat 获取文件的 etag
|
@@ -48,6 +48,6 @@ export async function write(file, data, opts) {
|
|
48
48
|
* @returns file stat etag
|
49
49
|
*/
|
50
50
|
export async function statTag(filePath) {
|
51
|
-
|
52
|
-
|
51
|
+
let stat = await fs.stat(filePath);
|
52
|
+
return `${stat.size.toString(16)}-${stat.mtimeMs.toString(16)}`;
|
53
53
|
}
|