jcubic
jcubic

Reputation: 66518

Convert CP437 using JavaScript Encoding API in Browser

Is there a way to convert CP437 to UTF8 in browser using new Encoding API?

I've tried this:

decoder = new TextDecoder('CP437');
decoder = new TextDecoder('IBM437');

but got error:

Uncaught RangeError: Failed to construct 'TextDecoder': The encoding label provided ('IBM437') is invalid. at :1:11

I've also tried with dashes CP-437 and IBM-437.

On GNU/Linux I can use iconv, I've found project iconv-js, but it seems it only convert one encoding.

Is compiling iconv to JavaScript using Emscripten the only option?

Upvotes: 3

Views: 2364

Answers (1)

jcubic
jcubic

Reputation: 66518

Encoding API is limited and don't support CP437. So the process of conversion look like this:

create empty npm project using

npm init

then install

npm install -g browserify
npm install iconv-lite buffer-shims

create index.js file with:

window.iconv = require('iconv-lite');
window.Buffer = require('buffer-shims');

run

browserify -o iconv.js index.js

and now you have browser version of iconv lite library (in iconv.js file) that will work from browser.

With it you can run:

 document.getElementById('file').addEventListener('change', function(event) {
     var reader = new FileReader();
     reader.onload = function(event) {
         var utf8_str = iconv.decode(Buffer.from(event.target.result), 'CP437');
     };
     reader.readAsArrayBuffer(event.target.files[0]);
 });

you will need to have:

<input id="file" type="file" />

and

<meta charset="utf-8"/>

so iconv-lite can convert string to utf-8, which is the only valid charset.

If you want already Built JS file, you can access my static assets github repo using jsdelivr:

https://cdn.jsdelivr.net/gh/jcubic/static@master/js/iconv.js

Upvotes: 3

Related Questions