-
Notifications
You must be signed in to change notification settings - Fork 0
/
NodeFileUtils.ts
33 lines (28 loc) · 981 Bytes
/
NodeFileUtils.ts
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
// Copyright (c) 2023. Heusala Group Oy <info@heusalagroup.fi>. All rights reserved.
import { writeFile, unlink, rename } from 'fs/promises';
import { LogService } from "../core/LogService";
const LOG = LogService.createLogger( 'NodeFileUtils' );
export class NodeFileUtils {
public static async atomicWriteFile (
name : string,
data : Buffer,
encoding : BufferEncoding = "utf8"
) : Promise<void> {
const now = (new Date()).getTime();
const tempFile = `${name}.${now}`;
let doUnlink = true;
try {
await writeFile(tempFile, data, encoding);
await rename(tempFile, name);
doUnlink = false;
} finally {
if ( doUnlink ) {
try {
await unlink(tempFile);
} catch (err) {
LOG.warn(`Warning! Could not remove temp file: ${tempFile}`);
}
}
}
}
}