Created
January 17, 2016 16:10
-
-
Save surr-name/05dfb0ab9ef09c2b7d1a to your computer and use it in GitHub Desktop.
promise wrapped ( with progress ) get random bytes from /dev/random
This file contains 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
var | |
Q = require('q'), | |
fs = require('fs'); | |
function get ( o ) { | |
var requiredLength, SOURCE; | |
if ( typeof o === 'object' ) { | |
requiredLength = o.length; | |
SOURCE = o.source || '/dev/random'; | |
} else { | |
requiredLength = o; | |
SOURCE = '/dev/random'; | |
} | |
var D = Q.defer(); | |
var fd = fs.open(SOURCE, 'r', function (error, fd){ | |
if ( error ) D.reject(error); | |
var stream = fs.createReadStream(SOURCE, {fd : fd}), | |
isDone = false, | |
result = new Buffer(0), | |
oldPercents = 0, | |
currentPercents = 0; | |
stream.on('readable', function () { | |
if ( isDone ) return; | |
var chunk = stream.read(); | |
if ( chunk === null ) { | |
isDone = true; | |
D.reject('unexpected end of ' + SOURCE + ' stream'); | |
} | |
result = Buffer.concat([result, chunk]); | |
currentPercents = Math.floor(result.length/requiredLength*100); | |
if ( currentPercents >= 100 ) { | |
currentPercents = 100; | |
isDone = true; | |
result = result.slice(0, requiredLength); | |
return closeFd(fd) | |
.then(D.resolve.bind(D, result)) | |
.fail(D.reject.bind(D)); | |
} | |
if ( oldPercents !== currentPercents ) { | |
oldPercents = currentPercents; | |
D.notify(currentPercents); | |
} | |
}); | |
stream.on('end', function () { | |
isDone = true; | |
D.reject('unexpected end of ' + SOURCE + ' stream'); | |
}); | |
stream.on('error', function (error) { | |
isDone = true; | |
D.reject(error); | |
}); | |
}); | |
return D.promise; | |
} | |
function closeFd ( fd ) { | |
var D = Q.defer(); | |
fs.close(fd, function(error){ | |
error | |
? D.reject(error) | |
: D.resolve(); | |
}); | |
return D.promise; | |
} | |
module.exports.get = get; | |
// ---------------------------------------------------------------------- usage: | |
var | |
StringDecoder = require('string_decoder').StringDecoder, | |
decoder = new StringDecoder('base64'); | |
get(1024) | |
.then(function(buffer){ | |
var string = decoder.write(buffer); | |
console.log('[DONE] : %s bytes', string.length); | |
//console.log('\n\n', string); | |
}) | |
.fail(function(error){ | |
console.log('[ERROR] : ', error); | |
}) | |
.progress(function(progress){ | |
console.log('[PROGRESS] : %s%', progress); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment