index.js 613 B

12345678910111213141516171819202122232425262728
  1. 'use strict';
  2. var Buffer = require('buffer').Buffer;
  3. function hasFrom() {
  4. // Node versions 5.x below 5.10 seem to have a `from` method
  5. // However, it doesn't clone Buffers
  6. // Luckily, it reports as `false` to hasOwnProperty
  7. return (Buffer.hasOwnProperty('from') && typeof Buffer.from === 'function');
  8. }
  9. function cloneBuffer(buf) {
  10. if (!Buffer.isBuffer(buf)) {
  11. throw new Error('Can only clone Buffer.');
  12. }
  13. if (hasFrom()) {
  14. return Buffer.from(buf);
  15. }
  16. var copy = new Buffer(buf.length);
  17. buf.copy(copy);
  18. return copy;
  19. }
  20. cloneBuffer.hasFrom = hasFrom;
  21. module.exports = cloneBuffer;