node.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > node.js > nodejs base64 编码解码

nodejs之base64编码解码问题

作者:liyinchi1988

这篇文章主要介绍了nodejs之base64编码解码问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

nodejs base64 编码解码

普通字符串

编码

var b = new Buffer('JavaScript');
var s = b.toString('base64');
// SmF2YVNjcmlwdA==

解码:

var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();
// JavaScript

编码解码并转成hex

var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString('hex');
// 4a617661536372697074
var b = new Buffer('4a617661536372697074', 'hex')
var s = b.toString('utf8');
// JavaScript

编码解码图片

var fs = require('fs');
 
// function to encode file data to base64 encoded string
function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}
 
// function to create file from base64 encoded string
function base64_decode(base64str, file) {
    // create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
    var bitmap = new Buffer(base64str, 'base64');
    // write buffer to file
    fs.writeFileSync(file, bitmap);
    console.log('******** File created from base64 encoded string ********');
}
 
// convert image to base64 encoded string
var base64str = base64_encode('kitten.jpg');
console.log(base64str);
// convert base64 string back to image 
base64_decode(base64str, 'copy.jpg');

nodejs 操作base64

node 对字符串 图片 base64 编码解码。

/*
	对普通的字符串 进行base64
*/
var b = new Buffer('abceAdf123');
var s = b.toString('base64');
console.log(s); // YWJjZUFkZjEyMw==

let str = "7b3a51166a197c983519096085cebc70d2710146a67691937b2bd3efea91c6f6";
let s1 = new Buffer(str).toString('base64'); 
// N2IzYTUxMTY2YTE5N2M5ODM1MTkwOTYwODVjZWJjNzBkMjcxMDE0NmE2NzY5MTkzN2IyYmQzZWZlYTkxYzZmNg==
console.log(s1);

/*
	解码base64
*/
var b = new Buffer('YWJjZUFkZjEyMw==', 'base64')
var s2 = b.toString('utf8'); // hex => 转成十六进制

console.log(s2); // abceAdf123

// utf-8
var b = new Buffer('N2IzYTUxMTY2YTE5N2M5ODM1MTkwOTYwODVjZWJjNzBkMjcxMDE0NmE2NzY5MTkzN2IyYmQzZWZlYTkxYzZmNg==', 'base64')
var s3 = b.toString('utf8');

console.log(s3);

/*对图片的base64*/
var fs = require('fs');

function base64_encode(file) {
	var 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);
}

var base64str = base64_encode('a.png');
console.log(base64str);
base64_decode(base64str, 'a.copy.png');

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文