index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. var os = require('os');
  3. var equals = require('buffer-equal');
  4. var cr = new Buffer('\r\n');
  5. var nl = new Buffer('\n');
  6. /**
  7. * Append a buffer to another buffer ensuring to preserve line ending characters.
  8. *
  9. * ```js
  10. * console.log([appendBuffer(new Buffer('abc\r\n'), new Buffer('def')).toString()]);
  11. * //=> [ 'abc\r\ndef\r\n' ]
  12. *
  13. * console.log([appendBuffer(new Buffer('abc\n'), new Buffer('def')).toString()]);
  14. * //=> [ 'abc\ndef\n' ]
  15. *
  16. * // uses os.EOL when a line ending is not found
  17. * console.log([appendBuffer(new Buffer('abc'), new Buffer('def')).toString()]);
  18. * //=> [ 'abc\ndef' ]
  19. * * ```
  20. * @param {Buffer} `buf` Buffer that will be used to check for an existing line ending. The suffix is appended to this.
  21. * @param {Buffer} `suffix` Buffer that will be appended to the buf.
  22. * @return {Buffer} Final Buffer
  23. * @api public
  24. */
  25. module.exports = function appendBuffer(buf, suffix) {
  26. if (!suffix || !suffix.length) {
  27. return buf;
  28. }
  29. var eol;
  30. if (equals(buf.slice(-2), cr)) {
  31. eol = cr;
  32. } else if (equals(buf.slice(-1), nl)) {
  33. eol = nl;
  34. } else {
  35. return Buffer.concat([buf, new Buffer(os.EOL), new Buffer(suffix)]);
  36. }
  37. return Buffer.concat([buf, new Buffer(suffix), eol]);
  38. };