- TextDecoder и TextEncoder
- TextEncoder
- Javascript convert utf 8 to windows 1251
- Usage
- Basic API
- Streaming API
- Supported encodings
- Encoding/decoding speed
- BOM handling
- UTF-16 Encodings
- UTF-32 Encodings
- Other notes
- Testing
- TextDecoder
- Constructor
- Instance properties
- Instance methods
- Examples
- Representing text with typed arrays
- Handling non-UTF8 text
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- javascript utf 8 windows 1251
- Более новые статьи:
TextDecoder и TextEncoder
Что если бинарные данные фактически являются строкой? Например, мы получили файл с текстовыми данными.
Встроенный объект TextDecoder позволяет декодировать данные из бинарного буфера в обычную строку.
Для этого прежде всего нам нужно создать сам декодер:
let decoder = new TextDecoder([label], [options]);
- label – тип кодировки, utf-8 используется по умолчанию, но также поддерживаются big5 , windows-1251 и многие другие.
- options – объект с дополнительными настройками:
- fatal – boolean, если значение true , тогда генерируется ошибка для невалидных (не декодируемых) символов, в ином случае (по умолчанию) они заменяются символом \uFFFD .
- ignoreBOM – boolean, если значение true , тогда игнорируется BOM (дополнительный признак, определяющий порядок следования байтов), что необходимо крайне редко.
…и после использовать его метод decode:
let str = decoder.decode([input], [options]);
- input – бинарный буфер ( BufferSource ) для декодирования.
- options – объект с дополнительными настройками:
- stream – true для декодирования потока данных, при этом decoder вызывается вновь и вновь для каждого следующего фрагмента данных. В этом случае многобайтовый символ может иногда быть разделён и попасть в разные фрагменты данных. Это опция указывает TextDecoder запомнить символ, на котором остановился процесс, и декодировать его со следующим фрагментом.
let uint8Array = new Uint8Array([72, 101, 108, 108, 111]); alert( new TextDecoder().decode(uint8Array) ); // Hello
let uint8Array = new Uint8Array([228, 189, 160, 229, 165, 189]); alert( new TextDecoder().decode(uint8Array) ); // 你好
Мы можем декодировать часть бинарного массива, создав подмассив:
let uint8Array = new Uint8Array([0, 72, 101, 108, 108, 111, 0]); // Возьмём строку из середины массива // Также обратите внимание, что это создаёт только новое представление без копирования самого массива. // Изменения в содержимом созданного подмассива повлияют на исходный массив и наоборот. let binaryString = uint8Array.subarray(1, -1); alert( new TextDecoder().decode(binaryString) ); // Hello
TextEncoder
TextEncoder поступает наоборот – кодирует строку в бинарный массив.
Имеет следующий синтаксис:
Javascript convert utf 8 to windows 1251
Usage
Basic API
var iconv = require('iconv-lite'); // Convert from an encoded buffer to a js string. str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); // Convert from a js string to an encoded buffer. buf = iconv.encode("Sample input string", 'win1251'); // Check if encoding is supported iconv.encodingExists("us-ascii")
Streaming API
// Decode stream (from binary data stream to js strings) http.createServer(function(req, res) var converterStream = iconv.decodeStream('win1251'); req.pipe(converterStream); converterStream.on('data', function(str) console.log(str); // Do something with decoded strings, chunk-by-chunk. >); >); // Convert encoding streaming example fs.createReadStream('file-in-win1251.txt') .pipe(iconv.decodeStream('win1251')) .pipe(iconv.encodeStream('ucs2')) .pipe(fs.createWriteStream('file-in-ucs2.txt')); // Sugar: all encode/decode streams have .collect(cb) method to accumulate data. http.createServer(function(req, res) req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) assert(typeof body == 'string'); console.log(body); // full request body string >); >);
Supported encodings
- All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex.
- Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap, utf32, utf32-le, and utf32-be.
- All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. Aliases like ‘latin1’, ‘us-ascii’ also supported.
- All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP.
Most singlebyte encodings are generated automatically from node-iconv. Thank you Ben Noordhuis and libiconv authors!
Multibyte encodings are generated from Unicode.org mappings and WHATWG Encoding Standard mappings. Thank you, respective authors!
Encoding/decoding speed
Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). Note: your results may vary, so please always check on your hardware.
operation iconv@2.1.4 iconv-lite@0.4.7 ---------------------------------------------------------- encode('win1251') ~96 Mb/s ~320 Mb/s decode('win1251') ~95 Mb/s ~246 Mb/s
BOM handling
- Decoding: BOM is stripped by default, unless overridden by passing stripBOM: false in options (f.ex. iconv.decode(buf, enc, ) ). A callback might also be given as a stripBOM parameter — it’ll be called if BOM character was actually found.
- If you want to detect UTF-8 BOM when decoding other encodings, use node-autodetect-decoder-stream module.
- Encoding: No BOM added, unless overridden by addBOM: true option.
UTF-16 Encodings
This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be smart about endianness in the following ways:
- Decoding: uses BOM and ‘spaces heuristic’ to determine input endianness. Default is UTF-16LE, but can be overridden with defaultEncoding: ‘utf-16be’ option. Strips BOM unless stripBOM: false .
- Encoding: uses UTF-16LE and writes BOM by default. Use addBOM: false to override.
UTF-32 Encodings
This library supports UTF-32LE, UTF-32BE and UTF-32 encodings. Like the UTF-16 encoding above, UTF-32 defaults to UTF-32LE, but uses BOM and ‘spaces heuristics’ to determine input endianness.
- The default of UTF-32LE can be overridden with the defaultEncoding: ‘utf-32be’ option. Strips BOM unless stripBOM: false .
- Encoding: uses UTF-32LE and writes BOM by default. Use addBOM: false to override. ( defaultEncoding: ‘utf-32be’ can also be used here to change encoding.)
Other notes
When decoding, be sure to supply a Buffer to decode() method, otherwise bad things usually happen.
Untranslatable characters are set to � or ?. No transliteration is currently supported.
Node versions 0.10.31 and 0.11.13 are buggy, don’t use them (see #65, #77).Testing
$ git clone git@github.com:ashtuchkin/iconv-lite.git $ cd iconv-lite $ npm install $ npm test $ # To view performance: $ node test/performance.js $ # To view test coverage: $ npm run coverage $ open coverage/lcov-report/index.html
TextDecoder
The TextDecoder interface represents a decoder for a specific text encoding, such as UTF-8 , ISO-8859-2 , KOI8-R , GBK , etc. A decoder takes a stream of bytes as input and emits a stream of code points.
Note: This feature is available in Web Workers
Constructor
Returns a newly constructed TextDecoder that will generate a code point stream with the decoding method specified in parameters.
Instance properties
The TextDecoder interface doesn’t inherit any properties.
A string containing the name of the decoder, which is a string describing the method the TextDecoder will use.
A Boolean indicating whether the error mode is fatal.
A Boolean indicating whether the byte order mark is ignored.
Instance methods
The TextDecoder interface doesn’t inherit any methods.
Returns a string containing the text decoded with the method of the specific TextDecoder object.
Examples
Representing text with typed arrays
This example shows how to decode a Chinese/Japanese character , as represented by five different typed arrays: Uint8Array , Int8Array , Uint16Array , Int16Array , and Int32Array .
let utf8decoder = new TextDecoder(); // default 'utf-8' or 'utf8' let u8arr = new Uint8Array([240, 160, 174, 183]); let i8arr = new Int8Array([-16, -96, -82, -73]); let u16arr = new Uint16Array([41200, 47022]); let i16arr = new Int16Array([-24336, -18514]); let i32arr = new Int32Array([-1213292304]); console.log(utf8decoder.decode(u8arr)); console.log(utf8decoder.decode(i8arr)); console.log(utf8decoder.decode(u16arr)); console.log(utf8decoder.decode(i16arr)); console.log(utf8decoder.decode(i32arr));
Handling non-UTF8 text
In this example, we decode the Russian text «Привет, мир!», which means «Hello, world.» In our TextDecoder() constructor, we specify the Windows-1251 character encoding, which is appropriate for Cyrillic script.
const win1251decoder = new TextDecoder("windows-1251"); const bytes = new Uint8Array([ 207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33, ]); console.log(win1251decoder.decode(bytes)); // Привет, мир!
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- The TextEncoder interface describing the inverse operation.
- A shim allowing to use this interface in browsers that do not support it.
- Node.js supports global export from v11.0.0
Found a content problem with this page?
This page was last modified on Feb 19, 2023 by MDN contributors.
Your blueprint for a better internet.
javascript utf 8 windows 1251
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
I need to convert string in UTF-8 to byte array in 1251 codepage in JavaScript. Google says nothing useful. Help 🙂
We have server and client. Server has userpasswords hased with SHA512 and 1251 codepage. Client (web browser) has to hash passwords (provided by user in plain text) with SHA512 and transmit it to the server. The problem is: browser works in UTF-8 encoding, and of course SHA512 in UFT-8 is not the same as SHA512 in 1251. Any Ideas?
Был случай, да он у каждого сайтостроителя был и будет всегда — это объявление кодировки javascript в html файле. в интернете есть много советов, но в основном многие из них устарели. читаем как сделал я.
В случае, если у вас файл на ява скрипте пришел в utf-8, а главный файл в windows-1251, то при выводе русских символов выходят крякозябры. Чтобы этого избежать делайте простое объявление кодировки в javascript:
Вот и все и будет вас счастье)
Более новые статьи:
- Типы данных в JavaScript (EcmaScript) знать обязательно перед его изучением этого языка на практике. …
«>Типы данных в EcmaScript — 23/02/2017 08:49
Часто мелочевые ошибки при программировании на javascript рушат весь сайт. Самые популярные будем разбирать в этой статье. …«>Популярные ошибки яваскрипта — 20/12/2015 16:38
Очень эффектно смотрится ссылка «Добавить сайт в избранное» и рядом можно еще фоновое завлекающее изображение поставить. Многие говорят, что это не вл …