forked from bdukes/Star-Wars-Ipsum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom.js
70 lines (57 loc) · 1.47 KB
/
random.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* from https://github.com/stellaeof/node_osrandom
* osrandom node package
* Provides simple access to os sources of randomness
*/
var fs=require('fs');
var randomFileName='/dev/urandom';
function dummyRandom(byteCount, callback) {
var err=new Error('No OS source of randomness found');
if (callback) return callback(err);
else throw err;
}
/**
* By definition reads from /dev/urandom do not block. Since they are just
* a cpu-bound dip below the kernel barrier, we use sync functions.
*/
function openRandomDevice(deviceFileName) {
var fd=fs.openSync(deviceFileName, 'r');
return function(byteCount, callback) {
var buffer=new Buffer(byteCount),
offset=0,
r;
if (callback) {
// Do it async
return asyncRead();
} else {
// Synchronous
while (offset<byteCount) {
offset+=fs.readSync(fd, buffer, offset, byteCount-offset, null);
}
return buffer;
}
// -- helpers
function asyncRead() {
fs.read(fd, buffer, offset, byteCount-offset, null, function(err, bytesRead) {
if (err) return callback(err);
offset+=bytesRead;
if (offset>=byteCount) return callback(null, buffer);
asyncRead();
});
}
};
}
function detect() {
// Check for presence of randomDevice
var randomStat;
try {
randomStat=fs.statSync(randomFileName);
} catch (e) {
randomStat=null;
}
if (randomStat&&randomStat.isCharacterDevice()) {
return openRandomDevice(randomFileName);
}
return dummyRandom;
}
module.exports=detect();