Base64 Encoding / Decoding in Node.js
So how do you encode a string to base64 is Node.js? Is there something easy like base64_encode() of PHP's?
Node.js
'being' JavaScript, has a more logical approach to encoding strings,
instead of having thousands of inconsistently defined global functions.
Here is how you encode normal text to base64 in Node.js:
var b = new Buffer('JavaScript');
var s = b.toString('base64');
// SmF2YVNjcmlwdA==
And here is how you decode base64 encoded strings:
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();
// JavaScript
If you are interested in the details of how the above examples worked, follow me.
The new Buffer() constructor requires a number, array or string as the first parameter, and an optional encoding type as the second parameter. The possible encoding types are ascii, utf8, ucs2, base64, binary, and hex; the default being utf8.
By passing the second parameter, we tell JavaScript that "the string you see is encoded in this particular format". Notice how we did that in the decoding example.
Once we have the encoded string, we call the toString() method on the string. If we don't pass the encoding type to toString(), JavaScript assumes we want to convert the object to utf8 encoded string by default. We can make it convert to other formats by passing the encoding type to toString().
Let's encode a base64 encoded string to hex:
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString('hex');
// 4a617661536372697074
Now decode it to something humans can read:
var b = new Buffer('4a617661536372697074', 'hex')
var s = b.toString('utf8');
// JavaScript
Once you get the basics of Buffer and encoding, you can use your knowledge of the File System module to encode files to base64 strings.
In this well-commented example we convert an image to base64 encoded string, and re-generate a copy of the image from the base64 encoded string.
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');
Fascinating?
I am sure you learnt not only how to encode and decode base64, but in many other formats as well. Have fun with encoding!
PS: utf8 is the superset of ascii. If you are limited to using characters on the standard English keyboard, you can use ascii; if you are dealing with 'exotic' characters and symbols like ⌘, こんにちは, Üdvözöljük etc., use utf.
Base64 Encoding / Decoding in Node.js的更多相关文章
- Node.js Base64 Encoding和Decoding
如何在Node.js中encode一个字符串呢?是否也像在PHP中使用base64_encode()一样简单? 在Node.js中有许多encoding字符串的方法,而不用像在JavaScript中那 ...
- 用node.js写个在Bash上对字符串进行Base64或URL的encode和decode脚本
一:自己这段时间经常要用到Base64编码和URL编码,写个编译型语言有点麻烦干脆就用node.js弄了个,弄好后在/etc/profile里加上alias就能完成工具的配置,先上代码: functi ...
- Node.js:Buffer浅谈
Javascript在客户端对于unicode编码的数据操作支持非常友好,但是对二进制数据的处理就不尽人意.Node.js为了能够处理二进制数据或非unicode编码的数据,便设计了Buffer类,该 ...
- 《深入浅出Node.js》第6章 理解 Buffer
@by Ruth92(转载请注明出处) 第6章 理解 Buffer ✁ 为什么需要 Buffer? 在 Node 中,应用需要处理网络协议.操作数据库.处理图片.接收上传文件等,在网络流和文件的操作中 ...
- Node.js 手册查询-1-核心模块方法
Node.js 学习手册 标签(空格分隔): node.js 模块 核心模块 核心模块是被编译成二进制代码,引用的时候只需require表示符即可 os 系统基本信息 os模块可提供操作系统的一些基本 ...
- [Node.js] Node + Redis 实现分布式Session方案
原文地址: http://www.moye.me/?p=565 Session是什么? Session 是面向连接的状态信息,是对 Http 无状态协议的补充. Session 怎么工作? Sessi ...
- Nodejs学习笔记(六)--- Node.js + Express 构建网站预备知识
目录 前言 新建express项目并自定义路由规则 如何提取页面中的公共部分? 如何提交表单并接收参数? GET 方式 POST 方式 如何字符串加密? 如何使用session? 如何使用cookie ...
- Node.js缓冲模块Buffer
前言 Javascript是为浏览器而设计的,能很好的处理unicode编码的字符串,但对于二进制或非unicode编码的数据就显得无能为力. Node.js继承Javascript的语言特性,同时又 ...
- Node.js缓冲器
纯JavaScript是Unicode友好的,但对二进制数据不是很好.当与TCP流或文件系统打交道时,有必要处理字节流. Node提供缓冲器类,它提供实例来存储原始数据相似的一个整数数组,但对应于在V ...
随机推荐
- 【单调栈】Bzoj 1012: 最大数maxnumber
1012: [JSOI2008]最大数maxnumber Time Limit: 3 Sec Memory Limit: 162 MBSubmit: 6255 Solved: 2676[Submi ...
- 【BZOJ】【1565】【NOI2009】PVZ 植物大战僵尸
网络流/最大权闭合子图+拓扑排序 感动死了>_<,一年多以前刚知道网络流的时候听说了这道名字很带感的题目,现在终于有实力切掉它了. 这题是最大权闭合子图模型的经典应用<_<,首 ...
- [CFgym]2015-2016 ACM-ICPC Pacific Northwest Regional Contest小结
*感谢两位浙江大佬带我飞 贴下成绩 div2 div1 *div2不是我打的上个厕所就5/11了 比赛小结 A [题目大意] 有n(n<=500)个机场,两两之间距离是g[i][j],每经停一个 ...
- POJ2406 Power Strings KMP算法
给你一个串s,如果能找到一个子串a,连接n次变成它,就把这个串称为power string,即a^n=s,求最大的n. 用KMP来想,如果存在的话,那么我每次f[i]的时候退的步数应该是一样多的 譬 ...
- JavaC 编译目录下所有的UTF-8编码的java文件
javac -encoding UTF-8 *.java
- Tomcat启用Gzip压缩
原理简介 HTTP 压缩可以大大提高浏览网站的速度,它的原理是,在客户端请求服务器对应资源后,从服务器端将资源文件压缩,再输出到客户端,由客户端的浏览器负责解压缩并 浏览.相对于普通的 ...
- linux入门教程(十) 文档的压缩与打包
在windows下我们接触最多的压缩文件就是.rar格式的了.但在linux下这样的格式是不能识别的,它有自己所特有的压缩工具.但有一种文件在windows和linux下都能使用那就是.zip格式的文 ...
- lintcode :数组剔除元素后的乘积
题目: 数组剔除元素后的乘积 给定一个整数数组A. 定义B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], 计算B的时候请不要使用除法. 样例 给出 ...
- lintcode:Find the Connected Component in the Undirected Graph 找出无向图汇总的相连要素
题目: 找出无向图汇总的相连要素 请找出无向图中相连要素的个数. 图中的每个节点包含其邻居的 1 个标签和 1 个列表.(一个无向图的相连节点(或节点)是一个子图,其中任意两个顶点通过路径相连,且不与 ...
- *[hackerrank]Maximizing XOR
https://www.hackerrank.com/contests/w1/challenges/maximizing-xor/ 找了半天规律,答案竟然是暴力,伤感.我找到的方法是利用规律2^x X ...