Base64
Base64 编码
,解码
库;
适用场景
- 二进制数据与 Base64 互转
- 字符串与 Base64 互转
install
npm i @cnwhy/base64
为何重复造轮子?
- 需要单纯的Base64的库,而且能在浏览器上使用; (利用node的
Buffer
对像的方法出局) - 支持字符串; (
btoa
, atob
只支持 Latin1); Base64
编/解码本该与字符串无关, 但现有库几乎只支持字符串;- 能用上
Tree-shaking
, 项目一般只用需要(encode
或 decode
), 我可不想copy代码; - javascript 字符串无损转换 (因为这一点, 现有库几乎全军覆没), 具体例子;
- 能应付异型
Base64
方案;
兼容性
通用, 对于不支持ArrayBuffer
的环境将会用Array
代替Uint8Array
.
什么! 你要兼容IE6?
也不是不行, 把 dist/Base64.umd.js
最后那句 'Object.defineProperty(exports, '__esModule', { value: true });' 删了就可以了.
使用
const { encode, decode, createEncode, createDecode } = require('@cnwhy/base64');
let str = '中国𐄡美国';
let b64 = encode(str);
console.log(b64);
let _str = decode(b64).toString();
console.log('string:', str === _str);
let buffer = new Uint8Array([0,255,127,33,0,5]);
let fb64 = encode(buffer);
let fu8arr = decode(fb64);
console.log('buffer:', Array.from(buffer).join() == Array.from(fu8arr).join());
const TABLE = 'xQh}s7*y~A|nkj4Bf%z1R,P+)mMS{(&EWCKegp6r!OX</LuY-l9^ZJ#cTU[vHda$';
const PAD = '.';
const Utf16Encode = function(str) {
let cods = str.split('').map(s => s.charCodeAt(0));
return new Uint8Array(new Uint16Array(cods).buffer);
}
const Utf16Decode = function(arr) {
let u16 = Array.from(new Uint16Array(arr.buffer));
return u16.map(c => String.fromCharCode(c)).join('');
}
const myEncode = createEncode(TABLE,PAD,Utf16Encode);
const myDecode = createDecode(TABLE,PAD,Utf16Decode);
console.log('\n自定义转码:');
let myb64 = myEncode(str);
console.log(myb64);
let my_str = myDecode(myb64).toString();
console.log('my:',str == my_str);
更多使用例子可以参看这篇;
API
Base64 = {
BASE64_TABLE: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
BASE64_URL_TABLE: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
PAD: "=";
utf8Encode(str:string):Uint8Array|number[];
utf8Decode(utf8arr:Uint8Array|number[]):string;
encode(input:string|ArrayBuffer|Uint8Array|number[]):string;
decode(base64str: string) => number[]|Uint8Array;
encodeURL(input:string|ArrayBuffer|Uint8Array|number[]):string;
decodeURL(base64str: string) => number[]|Uint8Array;
createEncode(strEncode: Function): (input: any) => string;
createEncode(table?: string[] | string, pad?: string, strEncode?: Function): (input: any) => string;
createDecode(strDecode: Function): (base64str: string) => Uint8Array | number[];
createDecode(table?: string[] | string, pad?: string, strDecode?: Function): (base64str: string) => Uint8Array | number[];
}
参考资料
https://tools.ietf.org/html/rfc4648;