Nodejs base64编码与解码

1、普通字符串

//编码

new Buffer(String).toString('base64');

//解码

new Buffer(base64Str, 'base64').toString();

2、十六进制Hex

//编码

new Buffer(String, 'base64').toString('hex');

//解码

new Buffer(base64Str, 'hex').toString('utf8');

3、图片

const fs = require('fs');

//编码

function base64_encode(file) {
    let bitmap = fs.readFileSync(file);
    return new Buffer(bitmap).toString('base64');
}

//解码

function base64_decode(base64str, file) {
    var bitmap = new Buffer(base64str, 'base64');
    fs.writeFileSync(file, bitmap);
}