Completed
Push — master ( d83c14...87c801 )
by Jan
16s queued 16s
created

src/api/read.ts   A

Complexity

Total Complexity 14
Complexity/F 2.33

Size

Lines of Code 60
Function Count 6

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 46
dl 0
loc 60
rs 10
c 0
b 0
f 0
wmc 14
mnd 8
bc 8
fnc 6
bpm 1.3333
cpm 2.3333
noi 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
B read.ts ➔ read 0 5 6
A read.ts ➔ readAsync 0 16 3
A read.ts ➔ readSync 0 6 2
1
import * as fs from 'fs'
2
import { getTagsFromBuffer } from '../TagsHelpers'
3
import { isFunction, isString } from '../util'
4
import { Tags, TagIdentifiers } from '../types/Tags'
5
import { Options } from '../types/Options'
6
7
export type ReadCallback = {
8
    (error: NodeJS.ErrnoException | Error, tags: null): void
9
    (error: null, tags: Tags | TagIdentifiers): void
10
}
11
12
/**
13
 * Read ID3-Tags from passed buffer/filepath
14
 */
15
export function read(filebuffer: string | Buffer, options?: Options): Tags
16
export function read(filebuffer: string | Buffer, callback: ReadCallback): void
17
export function read(
18
    filebuffer: string | Buffer, options: Options, callback: ReadCallback
19
): void
20
export function read(
21
    filebuffer: string | Buffer,
22
    optionsOrCallback?: Options | ReadCallback,
23
    callback?: ReadCallback
24
): Tags | TagIdentifiers | void {
25
    const options: Options =
26
        (isFunction(optionsOrCallback) ? {} : optionsOrCallback) ?? {}
27
    callback =
28
        isFunction(optionsOrCallback) ? optionsOrCallback : callback
29
30
    if (isFunction(callback)) {
31
        return readAsync(filebuffer, options, callback)
32
    }
33
    return readSync(filebuffer, options)
34
}
35
36
function readSync(filebuffer: string | Buffer, options: Options) {
37
    if (isString(filebuffer)) {
38
        filebuffer = fs.readFileSync(filebuffer)
39
    }
40
    return getTagsFromBuffer(filebuffer, options)
41
}
42
43
function readAsync(
44
    filebuffer: string | Buffer,
45
    options: Options,
46
    callback: ReadCallback
47
) {
48
    if (isString(filebuffer)) {
49
        fs.readFile(filebuffer, (error, data) => {
50
            if(error) {
51
                callback(error, null)
52
            } else {
53
                callback(null, getTagsFromBuffer(data, options))
54
            }
55
        })
56
    } else {
57
        callback(null, getTagsFromBuffer(filebuffer, options))
58
    }
59
}
60