Passed
Pull Request — filestream (#173)
by
unknown
05:02
created

util-file.ts ➔ fsReadAsync   A

Complexity

Conditions 1

Size

Total Lines 12
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 12
rs 9.8
c 0
b 0
f 0
cc 1
1
import * as fs from 'fs'
2
import { promisify } from 'util'
3
import { hrtime } from "process"
4
5
export const fsOpenPromise = promisify(fs.open)
6
export const fsReadPromise = promisify(fs.read)
7
export const fsClosePromise = promisify(fs.close)
8
export const fsWritePromise = promisify(fs.write)
9
export const fsUnlinkPromise = promisify(fs.unlink)
10
export const fsRenamePromise = promisify(fs.rename)
11
export const fsExistsPromise = promisify(fs.exists)
12
export const fsWriteFilePromise = promisify(fs.writeFile)
13
14
export async function fsReadAsync(
15
    fileDescriptor: number,
16
    buffer: Buffer,
17
    offset = 0
18
): Promise<number> {
19
    return (await fsReadPromise(
20
        fileDescriptor,
21
        buffer,
22
        offset,
23
        buffer.length,
24
        null
25
    )).bytesRead
26
}
27
28
/**
29
 * @returns true if the file existed
30
 */
31
export function unlinkIfExistSync(filepath: string) {
32
    const exist = fs.existsSync(filepath)
33
    if (exist) {
34
        fs.unlinkSync(filepath)
35
    }
36
    return exist
37
}
38
39
/**
40
 * @returns true if the file existed
41
 */
42
export async function unlinkIfExist(filepath: string) {
43
    const exist = await fsExistsPromise(filepath)
44
    if (exist) {
45
        await fsUnlinkPromise(filepath)
46
    }
47
    return exist
48
}
49
50
export function processFileSync<T>(
51
    filepath: string,
52
    flags: string,
53
    process: (fileDescriptor: number) => T
54
) {
55
    const fileDescriptor = fs.openSync(filepath, flags)
56
    try {
57
        return process(fileDescriptor)
58
    }
59
    finally {
60
        fs.closeSync(fileDescriptor)
61
    }
62
}
63
64
export async function processFileAsync<T>(
65
    filepath: string,
66
    flags: string,
67
    process: (fileDescriptor: number) => Promise<T>
68
): Promise<T> {
69
    const fileDescriptor = await fsOpenPromise(filepath, flags)
70
    try {
71
        return await process(fileDescriptor)
72
    }
73
    finally {
74
        await fsClosePromise(fileDescriptor)
75
    }
76
}
77
78
export function makeTempFilepath(filepath: string) {
79
    // A high-resolution time is required to avoid potential conflicts
80
    // when running multiple tests in parallel for example.
81
    // Date.now() resolution is too low.
82
    return `${filepath}.tmp-${hrtime.bigint()}`
83
}
84