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 ...
随机推荐
- php将数据库导出成excel的方法
<?php $fname = $_FILES['MyFile']['name']; $do = copy($_FILES['MyFile']['tmp_name'],$fname); if ($ ...
- 修改info
新增Key: NSLocationAlwaysUsageDescription 和 NSLocationWhenInUseUsageDescription ,这两个Key的值将分别用于描述应用程序 ...
- Get current time and date on Android
You could use: Calendar c =Calendar.getInstance();int seconds = c.get(Calendar.SECOND); There are pl ...
- 怎样开启SQL数据库服务
使用数据库时开启服务是需要的,我给大家具体介绍几种方式开启SQL Sever 服务.这几种我都用图文的形式用三个开启方式给你展示,对于不会开启服务的朋友可以学习下,这些前提是你的电脑安装了SQL数据库 ...
- java 非法字符过滤 , 半角/全角替换
java 非法字符过滤 , 半角/全角替换 package mjorcen.netty.test1; import java.io.UnsupportedEncodingException; publ ...
- 《剑指Offer》- 面试题3
<剑指Offer——名企面试官精讲典型编程题> 面试题3: 二维数组元素从左到右.从上到下递增,输入一个二维数组和一个整数, 查找该整数. 自己的思路:有序条件下进行查找,当然最简单 ...
- C# 中请求数据方式
#region 根据URL获取结果集 /// <summary> /// 根据URL获取结果集 默认为GET,如果数据量大了可以传入POST // ...
- MySQL主从关系设置(转)
来源:LAMP兄弟连 作者:李恺 http://***/php/bencandy.php?fid=70&id=635 要做MySQL主从关系的设置,那么就得有两台MySQL主机.所以在开始之前 ...
- 配置sql server2012属性 ms-help://MS.SQLCC.v10/MS.SQLSVR.v10.zh-CHS/s10de_5techref/html/6df812ad-4d80-4503-8a23-47719ce85624.htm
服务与服务器是两个不同的概念,服务器是提供服务的计算机,配置服务器主要是对内存.处理器.安全性等几个方面配置.由于SQL Server 2005服务器的设置参数比较多,这里选一些比较常用的介绍. 配置 ...
- python中精确输出JSON浮点数的方法
有时需要在JSON中使用浮点数,比如价格.坐标等信息.但python中的浮点数相当不准确, 例如下面的代码: 复制代码代码如下: #!/usr/bin/env python import json a ...