/
toBuffer.js
55 lines (48 loc) · 1.48 KB
/
toBuffer.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
/**
* toBuffer Module
* Convert value into a buffer
*
* @name node-sodium
* @author bmf
* @date 11/5/13
* @version $
*/
/* jslint node: true */
'use strict';
var re = /^(?:utf8|ascii|binary|hex|utf16le|ucs2|base64)$/
/**
* Convert value into a buffer
*
* @param {String|Buffer|Array} value a buffer, and array of bytes or a string that you want to convert to a buffer
* @param {String} [encoding] encoding to use in conversion if value is a string. Defaults to 'hex'
* @returns {*}
*/
function toBuffer(value, encoding) {
if( typeof value === 'string') {
encoding = encoding || 'hex';
if( !re.test(encoding) ) {
throw new Error('[toBuffer] bad encoding. Must be: utf8|ascii|binary|hex|utf16le|ucs2|base64');
}
try {
return new Buffer(value, encoding);
}
catch (e) {
throw new Error('[toBuffer] string value could not be converted to a buffer :' + e.message);
}
}
else if( typeof value === 'object' ) {
if( Buffer.isBuffer(value) ) {
return value;
}
else if( value instanceof Array ) {
try {
return new Buffer(value);
}
catch (e) {
throw new Error('[toBuffer] Array could not be converted to a buffer :' + e.message);
}
}
}
throw new Error('[toBuffer] unsupported type in value. Use Buffer, string or Array');
}
module.exports = toBuffer;