浏览器js和服务端nodejs,普通文本和base64文本互相转换

nodejs 普通文本转base64文本

const base64 = Buffer.from('你好啊,我叫herry菌', 'utf8').toString('base64');
console.log(base64)

 

nodejs base64文本转普通文本

const text = Buffer.from('5L2g5aW95ZWK77yM5oiR5pivaGVycnnoj4w=', 'base64').toString('utf-8');
console.log(text)

 

浏览器js 普通文本转base64文本

//浏览器js 文本转base64
function txtToBase64(text) {
  const data = new TextEncoder().encode(text);//文本转buffer数组
  return btoa(String.fromCharCode.apply(null, data));
}

 

浏览器js base64文本转普通文本

//浏览器js base64转普通文本
function base64ToTxt(base64Text) {
  const decodedText = atob(base64Text);
  return decodeURIComponent(escape(decodedText));
}

 

posted @ 2023-06-26 16:07  herry菌  阅读(19)  评论(0编辑  收藏  举报