-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
For more info, see LinusU/stream-file-type#6
- Loading branch information
1 parent
144d9ab
commit 57268ac
Showing
4 changed files
with
88 additions
and
66 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import { PassThrough, Transform } from 'node:stream'; | ||
import { fileTypeFromStream } from 'file-type'; | ||
|
||
import { AnyFn } from './types.js'; | ||
|
||
export class FileType extends Transform { | ||
#stream: PassThrough | null; | ||
#result: Promise<{ ext: string; mime: string } | null>; | ||
#transformCalled: boolean; | ||
|
||
constructor() { | ||
super(); | ||
this.#stream = new PassThrough(); | ||
|
||
this.#result = fileTypeFromStream(this.#stream).then( | ||
(value) => { | ||
this.#stream = null; | ||
return value || null; | ||
}, | ||
(err) => { | ||
this.#stream = null; | ||
return null; | ||
}, | ||
); | ||
} | ||
|
||
fileTypePromise() { | ||
return this.#result; | ||
} | ||
|
||
override _transform(chunk: any, _: any, cb: AnyFn) { | ||
this.#transformCalled = true; | ||
if (this.#stream != null) { | ||
this.#stream.write(chunk); | ||
} | ||
|
||
cb(null, chunk); | ||
} | ||
|
||
override _flush(cb: AnyFn) { | ||
if (this.#transformCalled) { | ||
this.#result.finally(() => this.finish(cb)); | ||
} else { | ||
this.finish(cb); | ||
} | ||
} | ||
|
||
protected finish(cb: AnyFn) { | ||
cb(null); | ||
this.#stream?.end(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters