|
1 |
| -import { createReadStream, promises } from 'fs'; |
| 1 | +import { createReadStream } from 'fs'; |
| 2 | +import { writeFile, stat } from 'fs/promises'; |
2 | 3 | import { parser } from 'stream-json';
|
3 | 4 | import { chain } from 'stream-chain';
|
4 | 5 | import Asm from 'stream-json/Assembler';
|
5 | 6 |
|
6 |
| -export const readJSONStream = <T = unknown>(filepath: string): Promise<T> => { |
7 |
| - const pipeline = chain([createReadStream(filepath), parser()]); |
| 7 | +export const readJSONStream = async <T = unknown>(filepath: string): Promise<T> => { |
| 8 | + // Check if the file exists and throw error before creating a stream |
| 9 | + await stat(filepath); |
| 10 | + |
| 11 | + const readStream = createReadStream(filepath); |
| 12 | + const pipeline = chain([readStream, parser()]); |
8 | 13 | const asm = Asm.connectTo(pipeline);
|
9 | 14 |
|
10 |
| - return new Promise((fulfill) => { |
11 |
| - asm.on('done', (data) => fulfill(data.current)); |
| 15 | + return new Promise((resolve, reject) => { |
| 16 | + asm.on('done', (data) => { |
| 17 | + if (data.current) { |
| 18 | + resolve(data.current); |
| 19 | + } else { |
| 20 | + reject(new Error('Invalid JSON file')); |
| 21 | + } |
| 22 | + }); |
12 | 23 | });
|
13 | 24 | };
|
14 | 25 |
|
15 | 26 | export async function writeJSON(filepath: string, data: Record<string, unknown>): Promise<void> {
|
16 |
| - return promises.writeFile(filepath, JSON.stringify(data)); |
| 27 | + return writeFile(filepath, JSON.stringify(data)); |
17 | 28 | }
|
0 commit comments