2024-04-16 09:22:41 -04:00
import { File } from 'buffer'
import NodeFormData from 'form-data'
import fs from 'fs'
import { open } from 'node:fs/promises'
import { basename } from 'node:path'
import { getMimeType } from './getMimeType.js'
export async function createStreamableFile (
path : string ,
2025-11-13 14:49:22 +00:00
typeOverride? : string ,
2024-04-16 09:22:41 -04:00
) : Promise < { file : File ; handle : fs.promises.FileHandle } > {
const name = basename ( path )
const handle = await open ( path )
const { type } = getMimeType ( path )
2025-11-13 14:49:22 +00:00
const file = new File ( [ ] , name , { type : typeOverride || type } )
2024-04-16 09:22:41 -04:00
file . stream = ( ) = > handle . readableWebStream ( )
const formDataNode = new NodeFormData ( )
formDataNode . append ( 'file' , fs . createReadStream ( path ) )
const contentLength = await new Promise ( ( resolve , reject ) = > {
formDataNode . getLength ( ( err , length ) = > {
if ( err ) {
reject ( err )
} else {
resolve ( length )
}
} )
} )
// Set correct size otherwise, fetch will encounter UND_ERR_REQ_CONTENT_LENGTH_MISMATCH
Object . defineProperty ( file , 'size' , { get : ( ) = > contentLength } )
return { file , handle }
}