| 222 | } |
| 223 | |
| 224 | function streamOnData(this: StreamState, chunk: string): void { |
| 225 | if (this.isFirstChunk) { |
| 226 | this.isFirstChunk = false |
| 227 | if (chunk.charCodeAt(0) === 0xfeff) { |
| 228 | chunk = chunk.slice(1) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | this.totalBytesRead += Buffer.byteLength(chunk) |
| 233 | if ( |
| 234 | !this.truncateOnByteLimit && |
| 235 | this.maxBytes !== undefined && |
| 236 | this.totalBytesRead > this.maxBytes |
| 237 | ) { |
| 238 | this.stream.destroy( |
| 239 | new FileTooLargeError(this.totalBytesRead, this.maxBytes), |
| 240 | ) |
| 241 | return |
| 242 | } |
| 243 | |
| 244 | const data = this.partial.length > 0 ? this.partial + chunk : chunk |
| 245 | this.partial = '' |
| 246 | |
| 247 | let startPos = 0 |
| 248 | let newlinePos: number |
| 249 | while ((newlinePos = data.indexOf('\n', startPos)) !== -1) { |
| 250 | if ( |
| 251 | this.currentLineIndex >= this.offset && |
| 252 | this.currentLineIndex < this.endLine |
| 253 | ) { |
| 254 | let line = data.slice(startPos, newlinePos) |
| 255 | if (line.endsWith('\r')) { |
| 256 | line = line.slice(0, -1) |
| 257 | } |
| 258 | if (this.truncateOnByteLimit && this.maxBytes !== undefined) { |
| 259 | const sep = this.selectedLines.length > 0 ? 1 : 0 |
| 260 | const nextBytes = this.selectedBytes + sep + Buffer.byteLength(line) |
| 261 | if (nextBytes > this.maxBytes) { |
| 262 | // Cap hit — collapse the selection range so nothing more is |
| 263 | // accumulated. Stream continues (to count totalLines). |
| 264 | this.truncatedByBytes = true |
| 265 | this.endLine = this.currentLineIndex |
| 266 | } else { |
| 267 | this.selectedBytes = nextBytes |
| 268 | this.selectedLines.push(line) |
| 269 | } |
| 270 | } else { |
| 271 | this.selectedLines.push(line) |
| 272 | } |
| 273 | } |
| 274 | this.currentLineIndex++ |
| 275 | startPos = newlinePos + 1 |
| 276 | } |
| 277 | |
| 278 | // Only keep the trailing fragment when inside the selected range. |
| 279 | // Outside the range we just count newlines — discarding prevents |
| 280 | // unbounded memory growth on huge single-line files. |
| 281 | if (startPos < data.length) { |