nodejs_buffer.concat

语法:Buffer.concat(list,totalLength);

  • list:要合并的Buffer数组,是必须的参数。

  • totalLength:合并后的list的Buffer实例的长度,是非必需的参数。

  • 返回值:返回合并后的新的Buffer实例的长度。如果list没有提供值或者totalLength为0则返回0;

提供totalLength与否的区别:不提供这个值,程序需要花费时间另行计算新的Buffer实例的总长度。提供后该值会强制转换为无符号整数。新的Buffer实例的长度最终由该值决定


const buf1=Buffer.alloc(10);
const buf2=Buffer.alloc(14);
const buf3=Buffer.alloc(18);
const totalLength=buf1.length+buf2.length+buf3.length;

console.log(totalLength);//42

const bufA=Buffer.concat([buf1,buf2,buf3],totalLength);
console.log(bufA);//<Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ///00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00>
console.log(bufA.length);//42
 
//新创建的Buffer的长度取决于Buffer.concat的第二个参数的值。
const bufB=Buffer.concat([buf1,buf2,buf3],(totalLength-40));
console.log(bufB);//<Buffer 00 00>
console.log(bufB.length);//2

Buffer.concat:

Buffer.concat = function (list, length) {
    if (!Array.isArray(list)) {
        throw new Error('Usage:Buffer.concat(list,[length])');
    }
    //list值不为数组的情况

    if (list.length === 0) {
        return new Buffer(0);
    } else if (list.length === 1) {
        return list[0];
    }
    //length值为0的情况返回一个不包含任何项的buffer实例
    //length值为1的情况下返回一个仅包含list数组第一项的buffer实例

    if (typeof length !== 'number') {
        //对于length不为undefined的情况,即length值没有被写入或者错误写入
        length = 0;
        for (let i = 0; i < list.length; i++) {
            var buf = list[i];
            length += buf.length;
        }
    }

    var buffer = new Buffer(length);
    var pos = 0;
    for (let i = 0; i < list.length; i++) {
        var buf = list[i];
        buf.copy(buffer, pos);
        pos += buf.length;
    }
    return buffer;
};
posted @ 2020-04-01 15:08  Syinho  阅读(702)  评论(0编辑  收藏  举报