mirror of
https://github.com/whyour/qinglong.git
synced 2026-07-01 04:40:38 +08:00
写入文件增加文件锁,避免竞争条件引起文件内容异常
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
import { lock } from 'proper-lockfile';
|
||||
import { writeFile, open } from 'fs/promises';
|
||||
import { fileExist } from '../config/util';
|
||||
|
||||
export async function writeFileWithLock(
|
||||
path: string,
|
||||
content: string | Buffer,
|
||||
options: Parameters<typeof writeFile>[2] = {},
|
||||
) {
|
||||
if (typeof options === 'string') {
|
||||
options = { encoding: options };
|
||||
}
|
||||
if (!(await fileExist(path))) {
|
||||
const fileHandle = await open(path, 'w');
|
||||
fileHandle.close();
|
||||
}
|
||||
const release = await lock(path, {
|
||||
retries: {
|
||||
retries: 10,
|
||||
factor: 2,
|
||||
minTimeout: 100,
|
||||
maxTimeout: 3000,
|
||||
},
|
||||
});
|
||||
await writeFile(path, content, { encoding: 'utf8', ...options });
|
||||
await release();
|
||||
}
|
||||
Reference in New Issue
Block a user