File size: 958 Bytes
5f83d86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
34
import { createReadStream } from 'fs';
import { Readable } from 'stream';
import { TextDecoderStream } from 'stream/web';

export async function decodeFileStream(
    fileStream: Readable,
    encoding: string = 'utf-8',
): Promise<string> {
    const decodeStream = new TextDecoderStream(encoding, { fatal: false, ignoreBOM: false });
    Readable.toWeb(fileStream).pipeThrough(decodeStream);
    const chunks = [];

    for await (const chunk of decodeStream.readable) {
        chunks.push(chunk);
    }

    return chunks.join('');
}


export async function readFile(
    filePath: string,
    encoding: string = 'utf-8',
): Promise<string> {
    const decodeStream = new TextDecoderStream(encoding, { fatal: false, ignoreBOM: false });
    Readable.toWeb(createReadStream(filePath)).pipeThrough(decodeStream);
    const chunks = [];

    for await (const chunk of decodeStream.readable) {
        chunks.push(chunk);
    }

    return chunks.join('');
}