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');

原文:http://www.cnblogs.com/nano/archive/2013/05/27/3101348.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM