Skip to content

Instantly share code, notes, and snippets.

@shrunyan
Created August 26, 2016 20:59
Show Gist options
  • Save shrunyan/4b3eb6858052271eeda3c7bec6a99b22 to your computer and use it in GitHub Desktop.
Save shrunyan/4b3eb6858052271eeda3c7bec6a99b22 to your computer and use it in GitHub Desktop.
Node.js module to sniff the bytes from a stream for mimetype detection
'use strict'
import stream from 'stream'
export default function sniff(rs, sniffLength = 16384) {
return new Promise((resolve, reject) => {
let buffer = Buffer.from([])
let ws = new stream.Writable()
ws._write = (chunk, encoding, cb) => {
if (chunk) {
buffer = Buffer.concat([buffer, chunk])
if (Buffer.byteLength(buffer) > sniffLength) {
rs.unpipe(ws)
return resolve(buffer)
}
}
cb()
}
ws.on('finish', () => {
resolve(buffer)
})
ws.on('error', reject)
rs.pipe(ws)
})
}
@shrunyan
Copy link
Author

Takes in a readable stream and then returns a promise that resolves to the first 16384 bytes. Can be used for sniffing the mimetype.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment