* Helper function to stream JSON data to a file. * @param targetPath The path to write the stream to. * @param data The data to stream. * @param prettyPrint Whether to format the JSON with indentation. * @returns Promise
(targetPath: string, data: any, prettyPrint = false)
| 200 | * @returns Promise<void> |
| 201 | */ |
| 202 | async function _streamDataToFile(targetPath: string, data: any, prettyPrint = false): Promise<void> { |
| 203 | // Stream data to avoid high memory usage for large JSON objects. |
| 204 | const fileWriteStream = fsSync.createWriteStream(targetPath, { encoding: "utf8" }) |
| 205 | |
| 206 | // JsonStreamStringify traverses the object and streams tokens directly |
| 207 | // The 'spaces' parameter adds indentation during streaming, not via a separate pass |
| 208 | // Convert undefined to null for valid JSON serialization (undefined is not valid JSON) |
| 209 | const stringifyStream = new JsonStreamStringify( |
| 210 | data === undefined ? null : data, |
| 211 | undefined, // replacer |
| 212 | prettyPrint ? "\t" : undefined, // spaces for indentation |
| 213 | ) |
| 214 | |
| 215 | return new Promise<void>((resolve, reject) => { |
| 216 | stringifyStream.on("error", reject) |
| 217 | fileWriteStream.on("error", reject) |
| 218 | fileWriteStream.on("finish", resolve) |
| 219 | stringifyStream.pipe(fileWriteStream) |
| 220 | }) |
| 221 | } |
| 222 | |
| 223 | export { safeWriteJson } |