({
readableStream,
maxEntriesToImport,
onProgress,
chunkInterval = 1048576, // send progress every 1MB
}: {
readableStream: NodeJS.ReadableStream;
maxEntriesToImport: number;
onProgress?: (progress: number) => Promise<void>;
chunkInterval?: number;
})
| 89 | |
| 90 | // Splits the stream into individual chunks split on newlines |
| 91 | async function streamToNdStrings({ |
| 92 | readableStream, |
| 93 | maxEntriesToImport, |
| 94 | onProgress, |
| 95 | chunkInterval = 1048576, // send progress every 1MB |
| 96 | }: { |
| 97 | readableStream: NodeJS.ReadableStream; |
| 98 | maxEntriesToImport: number; |
| 99 | onProgress?: (progress: number) => Promise<void>; |
| 100 | chunkInterval?: number; |
| 101 | }): Promise<string[]> { |
| 102 | return new Promise((resolve, reject) => { |
| 103 | const lines: string[] = []; |
| 104 | let bytesDownloaded = 0; |
| 105 | let lastReportedByteCount = 0; |
| 106 | let tempBuffer: Buffer = Buffer.alloc(0); |
| 107 | let numEntriesImported = 0; |
| 108 | |
| 109 | readableStream.on("data", (chunk: Buffer) => { |
| 110 | bytesDownloaded += chunk.byteLength; |
| 111 | |
| 112 | // Report progress |
| 113 | if (onProgress && bytesDownloaded - lastReportedByteCount >= chunkInterval) { |
| 114 | void onProgress(bytesDownloaded); |
| 115 | lastReportedByteCount = bytesDownloaded; |
| 116 | } |
| 117 | |
| 118 | // Combine with leftover buffer from previous chunk |
| 119 | chunk = Buffer.concat([tempBuffer, chunk]); |
| 120 | |
| 121 | let newlineIndex; |
| 122 | while ( |
| 123 | (newlineIndex = chunk.indexOf(0x0a)) !== -1 && |
| 124 | numEntriesImported < maxEntriesToImport |
| 125 | ) { |
| 126 | const line = chunk.slice(0, newlineIndex).toString("utf-8"); |
| 127 | lines.push(line); |
| 128 | chunk = chunk.slice(newlineIndex + 1); |
| 129 | numEntriesImported++; |
| 130 | } |
| 131 | |
| 132 | if (numEntriesImported >= maxEntriesToImport) { |
| 133 | // TODO: cancel the stream |
| 134 | resolve(lines); |
| 135 | return; |
| 136 | } |
| 137 | |
| 138 | // Save leftover data for next chunk |
| 139 | tempBuffer = chunk; |
| 140 | }); |
| 141 | |
| 142 | readableStream.on("end", () => { |
| 143 | if (tempBuffer.length > 0) { |
| 144 | lines.push(tempBuffer.toString("utf-8")); // add the last part |
| 145 | } |
| 146 | resolve(lines); |
| 147 | }); |
| 148 |
no test coverage detected