이 심하더라도 위의 답변에서 데스크톱 브라우저의 구현이 btoa()
및 atob()
과 일치하지 않았습니다.
const btoa = function(str){ return Buffer.from(str).toString('base64'); }
// returns "4pyT", yet in desktop Chrome would throw an error.
btoa('✓');
// returns "fsO1w6bCvA==", yet in desktop Chrome would return "fvXmvA=="
btoa(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));
Buffer
인스턴스는 UTF-8 by default으로 인코딩 된 문자열을 나타내거나 해석합니다. 이 예외가 발생합니다 대조적으로, 데스크탑 크롬, 당신은 심지어 입력 라틴 이외의 문자가 포함 된 문자열, btoa()
로 다양합니다 : 따라서 Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
을 명시 적 latin1
에 encoding type에서 설정해야 당신은 Node.js를하고 브라우저 사이베이스 64를 교환하려는 경우 ASCII 문자가 아닌 문자에서 작동하지 않습니다 여기에 게시
const btoaLatin1 = function(str) { return Buffer.from(str, 'latin1').toString('base64'); }
const atobLatin1 = function(b64Encoded) {return Buffer.from(b64Encoded, 'base64').toString('latin1');}
const btoaUTF8 = function(str) { return Buffer.from(str, 'utf8').toString('base64'); }
const atobUTF8 = function(b64Encoded) {return Buffer.from(b64Encoded, 'base64').toString('utf8');}
btoaLatin1('✓'); // returns "Ew==" (would be preferable for it to throw error because this is undecodable)
atobLatin1(btoa('✓')); // returns "\u0019" (END OF MEDIUM)
btoaUTF8('✓'); // returns "4pyT"
atobUTF8(btoa('✓')); // returns "✓"
// returns "fvXmvA==", just like desktop Chrome
btoaLatin1(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));
// returns "fsO1w6bCvA=="
btoaUTF8(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));
감사합니다! – Joey
누군가에게 도움이된다면, 이것을 모카 common.js에 넣어 두었습니다. global.btoa = function (str) {새로운 버퍼 (str) .toString ('base64');};''를 반환하면 내가 브라우저를 가지고있는 것처럼 콘솔에서 테스트 할 수 있습니다. – snapfractalpop
node.js와 브라우저 사이의 또 다른 사소한 차이점은 동형 이성미를 성취하기가 좀 더 어렵게 만듭니다. 대답을 주셔서 감사합니다, @ mscdex, 정말 도움이! (정직하게!) – Swivel