Last active
February 8, 2018 12:03
-
-
Save petamoriken/098ea34e33f5299186d3 to your computer and use it in GitHub Desktop.
これで文字コードのテーブルを用意しなくてすむよ!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* ArrayBuffer から文字列にデコードする | |
* @param {ArrayBuffer} buffer | |
* @param {string} charset | |
* @returns {Promise<string>} | |
*/ | |
async function decodeText(buffer, charset="utf-8") { | |
// Encoding API | |
if (window.TextDecoder) { | |
const decoder = new TextDecoder(charset); | |
return decoder.decode(buffer); | |
} | |
// FileReader API | |
return new Promise((resolve, reject) => { | |
const blob = new Blob([buffer], {type:`text/plain;charset=${charset}`}); | |
const reader = new FileReader(); | |
reader.onload = () => { | |
resolve(reader.result); | |
}; | |
reader.onerror = () => { | |
reject(reader.error); | |
} | |
reader.readAsText(blob, charset); | |
}); | |
} |
アプデした。
const buffer = (new Uint8Array([0x8f, 0x97, 0x91, 0x95, 0x82, 0xb5, 0x82, 0xbd, 0x82, 0xa2])).buffer;
decodeText(buffer, "shift_jis").then((text) => {
console.log(text); // 女装したい
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Blob の第二引数、指定しなくていいかもしれない。