Skip to content

Commit

Permalink
Add initial chunk in transform method.
Browse files Browse the repository at this point in the history
  • Loading branch information
Borewit committed Aug 2, 2024
1 parent 1bb5685 commit 72e1d95
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions core.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ export class FileTypeParser {
async toDetectionStream(stream, options) {
const {sampleSize = reasonableDetectionSizeInBytes} = options;
let detectedFileType;
let firstChunk = null;

// Create a new ReadableStream to manage locking issues
const transformStream = new TransformStream({
Expand All @@ -119,6 +120,7 @@ export class FileTypeParser {
try {
// Read the first chunk from the stream
const {value: chunk, done} = await reader.read(new Uint8Array(sampleSize));
firstChunk = chunk;
if (!done && chunk) {
try {
// Attempt to detect the file type from the chunk
Expand All @@ -132,23 +134,28 @@ export class FileTypeParser {
}
}

controller.enqueue(chunk); // Enqueue the initial chunk
firstChunk = chunk;
} catch (error) {
controller.error(error); // Handle errors during start
} finally {
reader.releaseLock(); // Ensure the reader is released
}
},
transform(chunk, controller) {
if (firstChunk) {
firstChunk = null;
controller.enqueue(firstChunk); // Enqueue the initial chunk
}

// Pass through the chunks without modification
controller.enqueue(chunk);
},
});

const finalStream = stream.pipeThrough(transformStream);
finalStream.fileType = detectedFileType;
const newStream = stream.pipeThrough(transformStream);
newStream.fileType = detectedFileType;

return finalStream;
return newStream;
}

check(header, options) {
Expand Down

0 comments on commit 72e1d95

Please sign in to comment.