新手求指点concat执行不成功,提示 buf.copy is not a function
发布于 8 年前 作者 fxyc87 8285 次浏览 来自 问答

代码

var t=[‘1’,‘2’,‘3’]; var buf=Buffer.concat(t); console.log(buf); 错误提示:

buffer.js:239 buf.copy(buffer, pos); ^

TypeError: buf.copy is not a function at Function.Buffer.concat (buffer.js:239:9) at Object.<anonymous> (c:\Users\xa87\WebstormProjects\jlc\t3.js:5:16) at Module._compile (module.js:397:26) at Object.Module._extensions…js (module.js:404:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:429:10) at startup (node.js:139:18) at node.js:999:3

Process finished with exit code 1

6 回复

t数组内部是字符类型不是Buffer类型,当然没有Buffer的方法。

var chunks = []; var size = 0; res.on(‘data’, function(chunk){ chunks.push(chunk); size += chunk.length; });

res.on(‘end’, function(){ var buf = Buffer.concat(chunks, size); var str = iconv.decode(buf, ‘utf8’); console.log(str); })

我也是网络上接收数据,按上这这个例子来的啊,

var req=http.get(options,function(res){
    res.setEncoding('binary');
    var t=[];
    var size=0;
    res.on('data',function(dat){
        t.push(dat);
        size+=dat.length;
        //console.log(dat);
    });
    res.on('end',function() {
        console.log('  合并长度:'+ t.length + "," + size)
        //var buf=Buffer.concat(t);
        var buf=new Buffer(size);
        var off=0;
        for(var j=0;j< t.length;j++){
            buf.write(t[j],off,t[j].length,'binary');
            off+=t[j].length;
        }
		
		
		这是我的部分代码,Buffer.concat(t);执行不成功,只好注释了,自己FOR循环来,
		上边网上的例子都说可以啊?

@coordcn

见我2楼,3楼,求指点

@fxyc87 检查下每个data是不是都是Buffer类型,不是Buffer类型自然没有copy方法。

你三楼buf.write(string, offset, length, encoding)就说明你res.on(‘data’, function(data){ })的data是string类型,你可能是开启了字符模式,而不是Buffer模式。

你三楼 res.setEncoding(‘binary’);可能就是开启stream字符模式的真凶。。。

var b1 = new Buffer([1,2,3]);
var b2 = new Buffer(["444","5555","6666"]);
var buffer = Buffer.concat([b1,b2],b1.length+b2.length);
console.log(buffer)
回到顶部