如何在Node.js中输出表情符号(在Windows上)?

bdu*_*kes 15 windows unicode console node.js emoji

在Windows上,控制台中有一些基本的表情符号支持,因此如果我键入,我可以获得单色字形,例如 ?. I can output a string from PowerShell or a C# console application or Python and they all show those characters fine enough.

However, from Node.js, I can only get a couple of emoji to display (e.g. ?),而不是其他表情符号(而不是 I see ?).但是,如果我throw是带有这些字符的字符串,它们会正确显示.

console.log('  ? ');
throw '  ? ';
Run Code Online (Sandbox Code Playgroud)

如果我运行上面的脚本,输出是

 ? ?

C:\Code\emojitest\emojitest.js:2
throw '  ? '; 
^
  ?
Run Code Online (Sandbox Code Playgroud)

无论如何,我可以正确输出那些表情符号而不会抛出错误?或者是否通过标准Node.js API在我可以使用的范围外发生异常?

Bri*_*xon 11

如果不更改libuv,您可能无法实现所需.当您(或控制台)写入stdout或写入stderrWindows并且流是TTY时,libuv会自行从UTF-8转换为UTF-16.在这样做时,它明确拒绝输出代理对,而是U+FFFD为BMP之外的任何代码点发出替换字符 .

这是uv/src/win/tty.c的罪魁祸首:

  /* We wouldn't mind emitting utf-16 surrogate pairs. Too bad, the */
  /* windows console doesn't really support UTF-16, so just emit the */
  /* replacement character. */
  if (utf8_codepoint > 0xffff) {
    utf8_codepoint = UNICODE_REPLACEMENT_CHARACTER;
  }
Run Code Online (Sandbox Code Playgroud)

throw,因为节点允许Windows做转换从UTF-8为UTF-16与显示正确的消息MultiByteToWideChar()(它发出代理对)编写消息到控制台之前.(参见PrintErrorString()src/node.cc.)