toBuffer.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * toBuffer Module
  3. * Convert value into a buffer
  4. *
  5. * @name node-sodium
  6. * @author bmf
  7. * @date 11/5/13
  8. * @version $
  9. */
  10. /* jslint node: true */
  11. 'use strict';
  12. var re = /^(?:utf8|ascii|binary|hex|utf16le|ucs2|base64)$/
  13. /**
  14. * Convert value into a buffer
  15. *
  16. * @param {String|Buffer|Array} value a buffer, and array of bytes or a string that you want to convert to a buffer
  17. * @param {String} [encoding] encoding to use in conversion if value is a string. Defaults to 'hex'
  18. * @returns {*}
  19. */
  20. function toBuffer(value, encoding) {
  21. if( typeof value === 'string') {
  22. encoding = encoding || 'hex';
  23. if( !re.test(encoding) ) {
  24. throw new Error('[toBuffer] bad encoding. Must be: utf8|ascii|binary|hex|utf16le|ucs2|base64');
  25. }
  26. try {
  27. return Buffer.from(value, encoding);
  28. }
  29. catch (e) {
  30. throw new Error('[toBuffer] string value could not be converted to a buffer :' + e.message);
  31. }
  32. }
  33. else if( typeof value === 'object' ) {
  34. if( Buffer.isBuffer(value) ) {
  35. return value;
  36. }
  37. else if( value instanceof Array ) {
  38. try {
  39. return Buffer.from(value);
  40. }
  41. catch (e) {
  42. throw new Error('[toBuffer] Array could not be converted to a buffer :' + e.message);
  43. }
  44. }
  45. }
  46. throw new Error('[toBuffer] unsupported type in value. Use Buffer, string or Array');
  47. }
  48. module.exports = toBuffer;