nodejs中buffer用+连接会强制转换成字符串?

nodejs接收post数据时,在request监听data事件时回调函数的参数(chunk)是buffer,但是用+连接后怎么会成为字符串?

//main.js
http.createServer(function(req,res){
    if(req.method=='POST'){
        var all = ''
        req.on('data',function(chunk){
            console.log(chunk)
            all+=chunk
            console.log('all:',all)
        })
        req.on('end',function(){
            res.end(all.toUpperCase())
        })
    }else{
        res.end()
    }
}).listen(port)

我使用 curl -d "user=Summer&passwd=12345678" "http://127.0.0.1:3000" 进行模拟请求时,命令行结果如下

<Buffer 75 73 65 72 3d 53 75 6d 6d 65 72 26 70 61 73 73 77 64 3d 31 32 33 34 35
36 37 38>
all: user=Summer&passwd=12345678
阅读 4.7k
2 个回答

req在监听data事件时,获取到的chunk是Buffer实例,但是由于你调用了all += chunk,这里其实隐藏了toString()的转换,因为在拼接字符串时程序会尝试着调用toString()来将两个数据合理化,其实 all += chunk 可以看成是 all += chunk.toString() 的写法。

具体看我下面的代码:

// 一个字母1个字节编码
const buffer1 = Buffer.from('Hello World');
console.log(buffer1); // <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>
console.log(buffer1.length); // 11
console.log(buffer1 + ''); // Hello World
console.log(buffer1.toString()); // Hello World
console.log(buffer1.toString() === buffer1 + ''); // true

// 一个汉字3个字节来编码
const buffer2 = Buffer.from('你好世界啊');
console.log(buffer2); // <Buffer e4 bd a0 e5 a5 bd e4 b8 96 e7 95 8c e5 95 8a>
console.log(buffer2.length); // 15
console.log(buffer2 + ''); // 你好世界啊
console.log(buffer2.toString()); // 你好世界啊
console.log(buffer2.toString() === buffer2 + ''); // true

Buffer实例,也可以类似看成是String实例,它也具有遍历方法,比如forEach():

const buffer3 = Buffer.from('Hello World');
// <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>
console.log(buffer3);
buffer3.forEach(byte => {
  // 依次输出 72,101,108, ...  
  console.log(byte); // 输出UTF-8编码,十进制
  // 依次输出 H, e, l, ...
  console.log(String.fromCharCode(byte)); // 获取真实的字符
});

可能有人会对上面字符的转化存在疑问,为什么H的表示形式中的Buffer的48转换成十进制的72了,这是因为Buffer中的字符是十六进制编码的8 + 64 = 72,合理。

学习了,多谢

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题