file.ts 2.31 KB
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;
    }
}