Node.js Base64 Encoding和Decoding

  如何在Node.js中encode一个字符串呢?是否也像在PHP中使用base64_encode()一样简单?

  在Node.js中有许多encoding字符串的方法,而不用像在JavaScript中那样定义各种不同的全局函数。下面是如何在Node.js中将一个普通字符串encode成Base64格式的代码:

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

  下面是decode base64字符串的代码:

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

  如果你想了解上面代码的实现细节,请接着往下看。

  构造函数new Buffer()的第一个参数可以是一个Number,Array或String。第二个参数为可选参数,用来表示encode的类型,可以是AscII, Utf8, Ucs2, Base64, Binary, 或Hex。默认值是Utf8。

  通过第二个参数,告诉程序给定的字符串是以哪种特定格式被encode的。注意上面decode的例子中我们传入的参数。

  我们通过toString()方法将encode的字符串转换成其它格式,默认为Utf8。指定不同的参数,可以转换成我们想要的格式。例如我们可以将Base64之后的字符串转换成Hex格式:

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

  然后通过下面的方式将其decode成人类能看懂的字符串:

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

  一旦掌握了基本的Buffer和encode,我们就可以通过Node.js的File module将文件encode成Base64字符串。

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

PS:Utf8是AscII的超集。如果你只能使用标准英文键盘上的字符,则可以使用AscII编码;但是如果你正在处理其它“外来”字符或符号,例如⌘, こんにちは, Üdvözöljük等,请使用Utf。

posted @ 2016-11-21 21:34  Jaxu  阅读(22565)  评论(0编辑  收藏  举报