nodejs笔记-Buffer

let buffer1 = Buffer.from("这是");
let buffer2 = Buffer.from("拼接");

// Buffer.copy
let bigBuffer = Buffer.alloc(9);
Buffer.prototype.copy = function(target,targetStart,sourceStart=0,sourceEnd=this.length){
    for(let i=0;i<sourceEnd-sourceStart;i++){
        target[targetStart+i] = this[sourceStart+i]
    }
}
buffer1.copy(bigBuffer,0,0,3);
buffer2.copy(bigBuffer,3);
console.log(bigBuffer.toString());

// Buffer.concat
Buffer.concat = function(list,totalLegnth = list.reduce((a,b)=>a+b.length,0)){
    let buffer = Buffer.alloc(totalLegnth);
    let index = 0;
    list.forEach(buff=>{
        buff.copy(buffer, index)
        index += buff.length;
    });
    return buffer;
}
let buffer=Buffer.concat([buffer1,buffer2]);
console.log(buffer.toString())

let fs = require("fs")
let path = require("path")
// 读流写流
function copy(source,target){
    let buffer = Buffer.alloc(3);
    let pos = 0;
    fs.open(source,"r",(err,rfd)=>{
        fs.open(target,"w",(err,wfd)=>{
            function next(){
                fs.read(rfd,buffer,0,3,pos,(err,bytesRead)=>{
                    pos+=bytesRead;
                    if(bytesRead>0){
                        fs.write(wfd,buffer,0,bytesRead,(err,writeen)=>{
                            next();
                        })
                    }else{
                        fs.close(rfd,()=>{});
                        fs.close(wfd,()=>{});
                    }
                })
            };
            next()
        })
    })
}