Skip to content

Wrapper over file-type that makes using it with streams easier

License

Notifications You must be signed in to change notification settings

freehunter-ltd/file-type-stream

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

file-type-stream

Build Status

Wrapper over file-type that makes using it with streams easier.

Install

npm install --save file-type-stream

Requires Node v6+

Usage

fileTypeStream(callback)

See ./test directory for usage examples.

import fileTypeStream from 'file-type-stream'
import { PassThrough } from 'stream'

// ...
// s3Client = ....
// ...

const through = new PassThrough()
readStream.pipe(fileTypeStream((type) => {
  // since transform streams buffer up to 16kb which
  // is enough to detect the file type, we get
  // the file type even through through hasn't been piped
  // anywhere yet.

  console.log('ext', type.ext)
  console.log('mime', type.mime)

  // E.g.:
  // We can use that info to open a write stream on aws s3
  // with the correct content type
  client.upload({
    ContentType: type.mime,
    Bucket: 'some-bucket',
    Key: 'some-key',
    Body: through,
  }, null, (err) => {
    // Upload completed!
  })
})).pipe(through)

The code above can be written a bit more intuitively with async/await:

import fileTypeStream from 'file-type-stream'
import { PassThrough } from 'stream'

// ...
// s3Client = ....
// ...

const upload = async (rs) => {
  const Body = new PassThrough()

  const { mime } = await new Promise(resolve => {
    rs.pipe(fileTypeStream(resolve)).pipe(Body)
  })
  const response = client.upload({
    Body,
    ContentType: mime,
    Bucket: 'some-bucket',
    Key: 'some-key',
  }).toPromise()

  console.log(response)
}

About

Wrapper over file-type that makes using it with streams easier

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%