Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to encode and decode a string in Base64 in node.js

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to encode and decode strings in Base64 in node.js". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

What is Base64 coding?

Base64 encoding is a method of converting data (usually binary) to the ASCII character set. Base64 is often mistaken for an encryption technology because it can hide data. It is 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.

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

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

How does Base64 work?

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

Calculate the 8-bit binary version of the input text

Regroup the 8-bit version of data into 6-bit units

Find the decimal version of each 6-bit binary block

The Base64 symbol corresponding to each decimal value is obtained by querying the Base64 coding table.

To better understand this concept, let's look at an example. Suppose 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 earlier, Base64 converts 8-bit binary into a set of data into a set of 6-bit data. This is because the Base64 format is only 64 characters: 26 uppercase letters, 26 lowercase letters, 10 numeric characters, and "+" and "/" symbols for line breaks.

Base64 does not use all the ASCII special characters, but only these. Note that some implementations of Base64 use special characters that are different from "+" and "/".

Going back to this example, let's divide the 8-bit data into 6-bit groups.

010001 110110 111100 100000 011101 110110 100101 101110

You will not always be able to divide the data into a complete 6-bit set, in which case you will have to manually populate 0.

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 coding table is as follows:

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

Why use Base64 encoding?

Sending information in binary format is sometimes risky because not all applications or network systems can handle the original binaries. On the other hand, the ASCII character set is well known and is very simple to deal with for most systems.

For example, an e-mail server requires text data, so ASCII is usually used. Therefore, if you want to send a picture or any other binary to an e-mail server, you first need to encode it in a text-based format, preferably ASCII. This is where Base64 coding is very convenient in converting binary data into the correct format.

Use Node.js to Base64 encode a string

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 use require statements to import applications to use Buffer objects.

In physical memory, a buffer is an immutable array of integers that can also perform many different encodings / decoders. These range from UTF-8, UCS2, Base64, and hexadecimal coding to another format, or from another format to UTF-8, UCS2, Base64, and hexadecimal. When you write code that processes and manipulates data, you may use the Buffer object at some point.

Look at the following example. Here, we will use the Buffer object to encode the text string to Base64. Save the following code in the encode-text.js file:

'use strict'; let data =' stackabuse.com'; let buff = new Buffer (data); / / the string let base64data = buff.toString ('base64') is interpreted in utf-8 encoding format by default; console.log (''+ data +'"converted to Base64 is"'+ base64data +'"')

In the above script, we create a new buffer object and pass it the string we want to convert to Base64. Then we call the "toString" method on the buffer object we just created and pass it "base64" as an argument. The "toString" method, which takes "base64" as a parameter, returns data as a Base64 string. Run the above code and you will see the output below.

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

In the output, we can see the string converted to Base64 and its raw data.

Use Node.js to decode Base64 strings

Decoding an Base64 string is very similar to encoding. You must create a new buffer object and pass two parameters to its constructor. The first parameter is the data in Base64, and the second parameter is "base64". Then you just need to call "toString" on the buffer object, but this time the parameter passed to the method will be "ascii" because this is the data type you want the Base64 data to convert to. Please review the following code snippet for reference.

'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 +'"')

Add data to the ascii.js file and save it. Here we use "Tm8gdG8gUmFjaXNt" as the Base64 input data. When this data is decoded, it should display "No to Racism".

Encode binary data as a Base64 string

As mentioned at the beginning of the article, the main purpose of Base64 encoding is to convert binary data into text format. Let's look at an example where we convert an image (binary data) to a Base64 string. Look at the following example.

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

In the above code, we load the image into the buffer through the readFileSync () method of the fs module. The rest of the process is similar to creating an Base64 string from a normal ASCII string.

When you run the above code, you will see the following output.

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

Although the actual image is very small (25x19), the output is still quite large, in part because Base64 increases the size of the data, as we mentioned earlier.

Decode a Base64 string into binary data

The reverse process here is very similar to the way we decoded Base64 strings in the previous section. The biggest difference is the output destination and how the data is written there. Let's look at this example:

'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' + 'YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly' + '93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAg' + 'ICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAg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HxLgcSDn97WgZPoND+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')

Here you can see that we start with the Base64 data (which can also be received from socket or some other communication line) and then load it into the Buffer object. When we create a buffer, we tell it that it is in base64 format, which allows the buffer to parse it accordingly for internal storage.

To save the data back to the original PNG format, we simply pass the Buffer object to our fs.writeFileSync method, which transforms it for us.

Conclusion

Base64 encoding is one of the most common ways to convert binary data into plain ASCII text. It is a very useful format for communicating between one or more systems that cannot easily handle binary data, such as images in HTML tags or Web requests.

In Node.js, we can easily convert Base64 strings to and from many other formats through the Buffer object.

This is the end of the content of "how to encode and decode a string in Base64 in node.js". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 299

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report