-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfs.mjs
More file actions
64 lines (58 loc) · 1.46 KB
/
fs.mjs
File metadata and controls
64 lines (58 loc) · 1.46 KB
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
// Filesystem utilities for the OpenCode companion.
import fs from "node:fs";
import path from "node:path";
/**
* Ensure a directory exists (recursive mkdir).
* @param {string} dirPath
*/
export function ensureDir(dirPath) {
fs.mkdirSync(dirPath, { recursive: true });
}
/**
* Read a JSON file, returning null on failure.
* @param {string} filePath
* @returns {any|null}
*/
export function readJson(filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
} catch {
return null;
}
}
/**
* Write a JSON file atomically (write to tmp then rename).
* @param {string} filePath
* @param {any} data
*/
export function writeJson(filePath, data) {
ensureDir(path.dirname(filePath));
const tmp = `${filePath}.tmp.${process.pid}`;
fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", "utf8");
fs.renameSync(tmp, filePath);
}
/**
* Append a line to a file.
* @param {string} filePath
* @param {string} line
*/
export function appendLine(filePath, line) {
ensureDir(path.dirname(filePath));
fs.appendFileSync(filePath, line + "\n", "utf8");
}
/**
* Read the last N lines of a file.
* @param {string} filePath
* @param {number} n
* @returns {string[]}
*/
export function tailLines(filePath, n = 10) {
try {
const content = fs.readFileSync(filePath, "utf8");
const lines = content.split("\n");
const nonEmpty = lines.filter((line) => line.length > 0);
return nonEmpty.slice(-n);
} catch {
return [];
}
}