A utility that takes a file and generates a collection of SHA1 hashes suitable for use in BitTorrent files.
pieces is a utility that takes a file (browser) or file path (node) and a piece length, and generates a collection of SHA1 hashes that can be used when creating BitTorrent files.
npm install pieces
var pieces = require'pieces'var size = Mathpow2 14 // 16kb// Typically you’ll get the File object from// an input[type=file], but you you could also// just create your own Blob.var input = documentcreateElement'input'inputtype = 'file'var file = etargetfiles0piecesfile size// Returns a Uint8Array of binary datavar data = arraywindowopenURLcreateObjectURLdatadocumentbodyappendChildinput
var pieces = require'pieces'var path = '/path/to/file'var size = Mathpow2 18 // 256kb// You should probably make sure the path// exists before running piecespiecespath size// Returns a Buffer of binary dataconsole.logbuffertoString
When you start processing larger files, you’ll notice that it takes a while for the callback to be fired (particularly in browsers). To make this more managable, the pieces object emits
Where the implementation differences are denoted with a pipe (ie. browser|server).
var pieces = require'pieces'var file|path = …var size = …piecesfile|path sizeon'progress'// percentage is a Number between 0 and 100on'data'// bytes is a Uint8Array|Buffer containing a SHA1on'end'// And we’re done.