node.js 为什么 console.log(buffer) 给我一个十六进制列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7337564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:33:19  来源:igfitidea点击:

Why does console.log(buffer) give me a hexadecimal list?

node.jscoffeescript

提问by Shamoon

Here is my CoffeeScript:

这是我的 CoffeeScript:

buffer = new Buffer 100
buffer[i] = i for i in [0..99]
console.log buffer

which compiles to

编译成

  var buffer, i;
  buffer = new Buffer(100);
  for (i = 0; i < buffer.length; i++) {
    buffer[i] = i;
  }
  console.log(buffer);

When I run it with node, I get the following output:

当我用 node 运行它时,我得到以下输出:

$ coffee exercise1
<Buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f 60 61 62 63>

instead of 0 to 99. Why is that?

而不是 0 到 99。这是为什么呢?

回答by Trevor Burnham

Ray nailed it in his comment. See the Buffer documentation; you have to specify an encodingargument (you probably want 'utf8') on a Buffer's toString.

雷在他的评论中指出了这一点。请参阅缓冲区文档;您必须在 Buffer 上指定一个encoding参数(您可能想要'utf8'toString

// coffeescript
console.log buffer.toString 'utf8'
// javascript
console.log(buffer.toString('utf8'));