Home  >  Article  >  Web Front-end  >  A brief discussion on how to Base64 encode and decode strings in nodejs

A brief discussion on how to Base64 encode and decode strings in nodejs

青灯夜游
青灯夜游forward
2021-09-07 11:21:215555browse

What is Base64 encoding? How does Base64 work? The following article will introduce to you how to use Node.js to Base64 encode and decode strings. I hope it will be helpful to you!

A brief discussion on how to Base64 encode and decode strings in nodejs

What is Base64 encoding?

Base64 encoding is a method of converting data (usually binary) into the ASCII character set. Base64 is often mistaken for an encryption technology because of its ability to hide data. It's worth emphasizing that Base64 is not an encryption or compression technology. In fact, the size of the Base64 encoded information is 1.3333 times the actual size of the original data. [Recommended learning: "nodejs Tutorial"]

Understanding: Suppose we have 6 ASCII characters, then the binary data is 6 * 8 = 48 (bits). If Base64 encoding is used, it will be divided into 48 / 6 = 8 (groups), and each group will correspond to an ASCII character. That is to say, after Base64 encoding, we will have 8 ASCII characters. Because data is converted into electrical signals when transmitted (although what you see are characters), the size of the data is calculated in bits. 8 ASCII characters are 8 * 8 = 64 (bits), 64 / 48 = 4 / 3 ≈ 1.3333. To sum up, the size of Base64 encoded information is 1.3333 times the actual size of the original data.

Base64 is the most widely used basic encoding technology, and the other two commonly used encoding schemes are Base16 and Base32.

How does Base64 work?

Converting data to base64 is a multi-step process. Here's how it works for text strings:

  1. Computes an 8-bit binary version of the input text;
  2. Regroups the 8-bit version into 6-bit units ;
  3. Find the decimal version of each 6-bit binary block;
  4. Get the Base64 symbol corresponding to each decimal value by querying the Base64 encoding table.

To understand this concept better, let’s look at an example. Let's say we have the string "Go win" and we want to convert it to a Base64 string. The first step is to convert this string to binary. The binary version of "Go win" is:

01000111 01101111 00100000 01110111 01101001 01101110

You can see here that each character is represented by 8 bits. However, as we said before, Base64 converts data from 8-bit bins to 6-bit bins. This is because the Base64 format has only 64 characters: 26 uppercase letters, 26 lowercase letters, 10 numeric characters, and the " " and "/" symbols for line breaks.

Base64 does not use all ASCII special characters, but only these few. Note that some implementations of Base64 use different special characters than " " and "/".

Back to this example, let us divide the 8-bit data into groups of 6 bits.

010001 110110 111100 100000 011101 110110 100101 101110

You won't always be able to split the data into complete 6-bit sets, in which case you will have to pad the 0's manually.

Now for each block above, we have to find its decimal value. These decimal values ​​are given below:

Binary Decimal 
010001 17 
110110 54 
111100 60 
100000 32 
011101 29 
110110 54 
100101 37 
101110 46

Finally, we have to look at the Base64 value of each decimal number we just calculated from the binary data. The Base64 encoding table looks like this:

A brief discussion on how to Base64 encode and decode strings in nodejs

Here you can see that 17 in decimal corresponds to "R", 54 in decimal corresponds to "2", and so on. Using this encoding table, we can see that the string "Go win" is encoded using Base64 as "R28gd2lu". You can verify this result using any online text to Base64 converter.

Why use Base64 encoding?

Sending information in binary format can sometimes be risky because not all applications or network systems can handle raw binary files. The ASCII character set, on the other hand, is well known and very simple to handle for most systems.

For example, email servers require text data, so ASCII is often used. So if you want to send a picture or any other binary file to an email server, you first need to encode it into a text-based format, preferably ASCII. This is where Base64 encoding comes in handy for converting binary data into the correct format.

Base64 encoding a string using Node.js

The easiest way to encode a Base64 string in Node.js is Through the Buffer object. In Node.js, Buffer is a global object, which means you don’t need to import it into your application using a require statement to use the Buffer object.

在物理内存中,缓冲区是一个不可变的整数数组,它也能够执行许多不同的编码/解码。这些包括到从 UTF-8、UCS2、Base64 和 十六进制编码到另外一种格式, 或者从另外一种格式编码到 UTF-8、UCS2、Base64 和 十六进制。当您编写处理和操作数据的代码时,您可能会在某个时候使用 Buffer 对象。

看看下面的例子。在这里,我们将使用 Buffer 对象将文本字符串编码为 Base64。将以下代码保存在“encode-text.js”文件中:

'use strict'; 

let data = 'stackabuse.com'; 
let buff = new Buffer(data); // 默认用 utf-8 编码格式解释字符串
let base64data = buff.toString('base64');
console.log('"' + data + '" converted to Base64 is "' + base64data + '"');

在上面的脚本中,我们创建了一个新的缓冲区对象并将我们想要转换为 Base64 的字符串传递给它。然后我们在刚刚创建的缓冲区对象上调用“toString”方法,并将“base64”作为参数传递给它。以“base64”为参数的“toString”方法将以 Base64 字符串的形式返回数据。运行上面的代码,你会看到下面的输出。

$ node encode-text.js 
"stackabuse.com" converted to Base64 is "c3RhY2thYnVzZS5jb20="

在输出中,我们可以看到转换为 Base64 的字符串和它的原始数据。

使用 Node.js 解码 Base64 字符串

解码 Base64 字符串与编码非常相似。您必须创建一个新的缓冲区对象并将两个参数传递给它的构造函数。第一个参数是 Base64 中的数据,第二个参数是“base64”。然后您只需在缓冲区对象上调用“toString”,但这次传递给该方法的参数将是“ascii”,因为这是您希望 Base64 数据转换为的数据类型。请查看以下代码片段以供参考。

'use strict'; 
let data = 'Tm8gdG8gUmFjaXNt'; 
let buff = new Buffer(data, 'base64'); 
let text = buff.toString('ascii'); 
console.log('"' + data + '" converted from Base64 to ASCII is "' + text + '"');

将数据添加到 “ascii.js” 文件并保存。这里我们使用了“Tm8gdG8gUmFjaXNt”作为 Base64 输入数据。当这些数据被解码时,它应该显示“No to Racism”。

将二进制数据编码为 Base64 字符串

正如文章开头提到的,Base64 编码的主要目的是将二进制数据转换为文本格式。让我们看一个示例,我们将图像(二进制数据)转换为 Base64 字符串。看看下面的例子。

'use strict'; 

const fs = require('fs'); 
let buff = fs.readFileSync('stack-abuse-logo.png'); 
let base64data = buff.toString('base64'); 
console.log('Image converted to base 64 is:\n\n' + base64data);

在上面的代码中,我们通过 fs 模块的 readFileSync() 方法将图像加载到缓冲区中。该过程的其余部分类似于从普通 ASCII 字符串创建 Base64 字符串。

当您运行上面的代码时,您将看到以下输出。

$ node encode-image.js Image converted to Base64 is: 
iVBORw0KGgoAAAANSUhEUgAAABkAAAATCAYAAABlcqYFAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAACXBIWXMAAAsTAAALEwEAmpwYAAABWWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA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QF6wvMWBq+pAkaskSnx4FFVUf0CNpcC797KizXQ4oAHhVdXJJ81F7j6kwUynPHlXDPdFB2fRj+KVK0KvT2rbp3uKYryJU11Cke8qqMuOoioeeJ1MPDYxM36m1cNSq4GdFx58RAWvbx8TrXnK4IgR16Em5GK4iqHi5GHHxLgcSDn97WgZPoND+GGZRpPYH85cgiiRQl1ltXxmFFQ5PuopP8TrW5ZyRcWp7AbmkeZefg5+N6PPnbRJdpw/YlfB0vQiPQZwVdZNtFZEVK6D1VTnccJlXzuqTjvOZiq6Rhj2KqLSJsofOHgIl8+t0/qsfDioxmSUWGjrRFzhYi/5Oynrdl3KXHIZDXtF6hil8R6I9FBV/RvDLnXKxSbAdVYhNeINXBMwmXWCTQGG2Y+Jj+dFrfEmiMAtmeowpo9ojTvkD+A/L1UJUMmiVfkuz6WTyZhFRJAgP33j3bsM5k/Fng68UP21hYJyyxZwLWuS2cKMfUSm3rhD0g4E2g197fwMZ+Bgt8rNe2iP2BhL5dgfFzrx8AfECEDdx45a0AAAAASUVORK5CYII=

虽然实际图像非常小(25x19),但输出仍然相当大,部分原因是 Base64 增加了数据的大小,正如我们之前提到的。

将 Base64 字符串解码为二进制数据

这里的反向过程与我们在前面部分中看到的解码 Base64 字符串的方式非常相似。最大的区别是输出目的地以及数据在那里写入的方式。让我们看看这个例子:

'use strict'; 
const fs = require('fs');

let buff = new Buffer(data, 'base64'); 
fs.writeFileSync('stack-abuse-logo-out.png', buff); 

let data = 'iVBORw0KGgoAAAANSUhEUgAAABkAAAATCAYAAABlcqYFAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAA' + 'CA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAACXBIWXMAAAsTAAALEwEAmpwYAAABWWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0' + 'YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA8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qO9PUkJFULnbIQyTm6ewu2hF+vnOIIUQwdGlg8f4QF6wvMWBq+pAkaskSnx4FFVUf0CNpcC797KizXQ4oAHh' + 'VdXJJ81F7j6kwUynPHlXDPdFB2fRj+KVK0KvT2rbp3uKYryJU11Cke8qqMuOoioeeJ1MPDYxM36m1cNSq4GdFx58RAWvbx8TrXnK4IgR16Em5G' + 'K4iqHi5GHHxLgcSDn97WgZPoND+GGZRpPYH85cgiiRQl1ltXxmFFQ5PuopP8TrW5ZyRcWp7AbmkeZefg5+N6PPnbRJdpw/YlfB0vQiPQZwVdZN' + 'tFZEVK6D1VTnccJlXzuqTjvOZiq6Rhj2KqLSJsofOHgIl8+t0/qsfDioxmSUWGjrRFzhYi/5Oynrdl3KXHIZDXtF6hil8R6I9FBV/RvDLnXKxS' + 'bAdVYhNeINXBMwmXWCTQGG2Y+Jj+dFrfEmiMAtmeowpo9ojTvkD+A/L1UJUMmiVfkuz6WTyZhFRJAgP33j3bsM5k/Fng68UP21hYJyyxZwLWuS' + '2cKMfUSm3rhD0g4E2g197fwMZ+Bgt8rNe2iP2BhL5dgfFzrx8AfECEDdx45a0AAAAASUVORK5CYII=';

console.log('Base64 image data converted to file: stack-abuse-logo-out.png');

在这里您可以看到我们从 Base64 数据(也可以从 socket 或其他一些通信线路接收)开始,然后将其加载到 Buffer 对象中。在创建缓冲区时,我们告诉它它是 base64 格式,这允许缓冲区相应地解析它以进行内部存储。

要将数据保存回原始 PNG 格式,我们只需将 Buffer 对象传递给我们的 fs.writeFileSync 方法,它就会为我们进行转换。

结论

Base64 编码是将二进制数据转换为纯 ASCII 文本的最常用方法之一。它是一种非常有用的格式,用于在一个或多个无法轻松处理二进制数据的系统之间进行通信,例如 HTML 标记中的图像或 Web 请求。

在 Node.js 中,我们可以通过 Buffer 对象来轻松完成 Base64 字符串与许多其他格式数据相互转换的工作。

英文原文地址:https://stackabuse.com/encoding-and-decoding-base64-strings-in-node-js/

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of A brief discussion on how to Base64 encode and decode strings in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete