Created
August 26, 2016 20:59
-
-
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
This file contains hidden or 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
'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) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Takes in a readable stream and then returns a promise that resolves to the first
16384
bytes. Can be used for sniffing the mimetype.