## `Node.js Base64 Encoding和Decoding`

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。

分类: Node.js/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值