file.ts
2.31 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
65
66
67
68
69
70
71
72
73
74
import fs from 'node:fs';
import path from 'node:path';
import { logger } from './logger';
import { FileInfo } from '../types/file-types';
/**
* Write file to the specified path
* @param filePath - The path to the file
* @param content - The content to write to the file
*/
/**
* 底层安全写入:对 Windows 上常见的文件锁(EPERM / EBUSY)做有限次指数退避重试。
* 锁可能来自:预览用的 vite、IDE/编辑器文件监视器、杀软实时扫描等。
* 非锁类错误(如路径非法、磁盘满)仍立即抛出。
* @param options 透传给 fs.writeFileSync 的编码/选项(如 'utf8')
*/
export function writeFileSyncSafe(
full: string,
content: string,
options?: BufferEncoding,
): void {
let lastErr: unknown;
for (let attempt = 0; attempt < 8; attempt++) {
try {
fs.writeFileSync(full, content, options);
return;
} catch (e) {
const code = (e as NodeJS.ErrnoException)?.code;
if (code === 'EPERM' || code === 'EBUSY') {
lastErr = e;
syncSleep(50 * Math.pow(2, attempt));
continue;
}
throw e;
}
}
throw lastErr;
}
export const writeFile = (folderPath: string, filePath: string, content: string) => {
if (!folderPath || !filePath || !content) {
return;
}
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
}
const full = path.join(folderPath, filePath);
writeFileSyncSafe(full, content);
};
/** 主线程同步休眠(Node 下 Atomics.wait 可用),用于写重试的退避。 */
function syncSleep(ms: number): void {
try {
const sab = new SharedArrayBuffer(4);
Atomics.wait(new Int32Array(sab), 0, 0, ms);
} catch {
/* 极端环境退化:忽略 */
}
}
/**
* Create multiple files from parsed data
*/
export function createFiles({ files, filePath }: { files: FileInfo[]; filePath: string }): void {
try {
for (const file of files) {
const dirPath = path.dirname(filePath);
writeFile(dirPath, file.filename, file.content);
}
} catch (error) {
logger.printErrorLog(`Failed to create files in ${filePath}: ${(error as Error).message}`);
throw error;
}
}