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