blob: a385570bbd2b39d5f483eeffd1912c35521f26b4 [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2
3var os = require('os');
4var equals = require('buffer-equal');
5var cr = new Buffer('\r\n');
6var 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
28module.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};