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 ...
随机推荐
- 非常实用的10个PHP高级应用技巧
PHP 独特的语法混合了 C.Java.Perl 以及 PHP 自创新的语法.它可以比 CGI或者Perl更快速的执行动态网页.用PHP做出的动态页面与其他的编程语言相比,PHP是将程序嵌入到HTML ...
- eclipse的android智能提示设置
eclipse的android智能提示设置 分类: android 技术2011-12-07 23:13 3069人阅读 评论(0) 收藏 举报 eclipseandroidtriggersjavaf ...
- pure.css
注释中address是纠正的意思 等价于correct/*! Pure v0.5.0 Copyright 2014 Yahoo! Inc. All rights reserved. Licensed ...
- [转载]C#中字典集合的两种遍历
Dictionary<string, string> dictionary = new Dictionary<string,string>(); foreach (string ...
- java 中 ==和equals 的区别
Java中equals和==的区别 java中的数据类型,可分为两类: 1.基本数据类型,也称原始数据类型.byte,short,char,int,long,float,double,boolea ...
- structs spring hibernate 三者之间有什么关系?
现在开发流行MVC模式,structs在C(控制器)中使用:hibernate在M(模型)中被使用:至于 spring ,最大的作用在于,structs.hibernate的对象,由于在各个层之间相互 ...
- POJ2406 Power Strings KMP算法
给你一个串s,如果能找到一个子串a,连接n次变成它,就把这个串称为power string,即a^n=s,求最大的n. 用KMP来想,如果存在的话,那么我每次f[i]的时候退的步数应该是一样多的 譬 ...
- IOS 视图控制对象生命周期-init、viewDidLoad、viewWillAppear、viewDidAppear、viewWillDisappear等的区别及用途
iOS视图控制对象生命周期-init.viewDidLoad.viewWillAppear.viewDidAppear.viewWillDisappear.viewDidDisappear的区别及用途 ...
- MessageBox.Show()如何换行
MessageBox.Show("你好!\n\r可以使用", "换行");
- Android ActionBar 关于tab的应用 以及 TabListener的方法详解
actionBar的tab标签应用以及TabListener的方法详解 package com.example.actionBarTest.actionBarTab; import android.a ...