File size: 904 Bytes
0e27770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
var crypto = require('crypto');

function srs(options, cb) {
	if (typeof(options) === 'function') {
		cb = options;
		options = {};
	} else {
		options = options || {};
	}

	var length = options['length'] || 32;
	var alphanumeric = options['alphanumeric'] || false;
	// async path
	if (cb) {
		crypto.randomBytes(length, function(err, buf) {
			if (err) {
				return cb(err);
			}
			return cb(null, _finish(buf));
		});
	}
	// sync path
	else {
		return _finish(crypto.randomBytes(length));
	}

	function _finish(buf) {
		var string = buf.toString('base64');
		if (alphanumeric === true) {
			string = string.replace(/[\W_]+/g, '');
		} else {
			string = string.replace(/\//g, '_').replace(/\+/g, '-');
		}
		if (string.length < length) {
			throw new Error(`Generated string is too short. Please catch this Error and try again.`);
		}
		return string.substr(0, length);
	}
};



module.exports = srs;