What encodings are available Node.js

2019-05-16 11:47发布

问题:

I'm trying to figure out what encodings are available in node.js.

The documentation (http://nodejs.org/api/buffer.html#buffer_new_buffer_str_encoding) says:

Allocates a new buffer containing the given str. encoding defaults to 'utf8'.

but nowhere is specified a list of available encodings. Maybe I missed it.

I'm working on script which should be able to output in wide range of encodings. So far I know only about utf8 as doc is saying :)

Thx, Jaro.

回答1:

From the same page:

Converting between Buffers and JavaScript string objects requires an explicit encoding method. Here are the different string encodings.

  • 'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.

  • Note that when converting from string to buffer, this encoding converts a null character ('\0' or '\u0000') into 0x20 (character code of a space). If you want to convert a null character into 0x00, you should use 'utf8'.

  • 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.

  • 'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.

  • 'ucs2' - Alias of 'utf16le'.

  • 'base64' - Base64 string encoding.

  • 'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.

  • 'hex' - Encode each byte as two hexadecimal characters.