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

发布时间 2023-06-26 16:14:07作者: herry菌

nodejs 普通文本转base64文本

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

 

nodejs base64文本转普通文本

const text = Buffer.from('eyJhIjoxLCJiIjoyfQ==', '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));
}