Node.js——Base64 編碼和解碼
緩衝物件可編碼並解碼為Base64字串。緩衝類可用於將字串編碼為一系列位元組。Buffer.from()方法將字串作為輸入,並將其轉換為Base64。
轉換後的位元組可再次更改為字串。toString()方法用於將Base64緩衝區轉換回字串格式。
語法
Buffer.from(string, [encoding]) object.toString(encoding)
引數
引數描述如下
- 字串 − 此輸入引數獲取用於編碼為 base64 格式的字串的輸入。
- 編碼 − 此輸入引數獲取用於編碼和解碼字串的編碼的輸入。
示例 1:編碼為 Base64
建立一個名為“base64.js”的檔案,並複製以下程式碼段。建立檔案後,使用命令“node base64.js”執行此程式碼。
// Base64 Encoding Demo Example
// String data to be encoded
let string = "TutorialsPoint";
// Creating the buffer object with utf8 encoding
let bufferObj = Buffer.from(string, "utf8");
// Encoding into base64
let base64String = bufferObj.toString("base64");
// Printing the base64 encoded string
console.log("The encoded base64 string is:", base64String);輸出
C:\home
ode>> node base64.js The encoded base64 string is: VHV0b3JpYWxzUG9pbnQ=
示例 2:解碼 Base64 為字串
// Base64 Encoding Demo Example
// Base64 Encoded String
let base64string = "VHV0b3JpYWxzUG9pbnQ=";
// Creating the buffer object with utf8 encoding
let bufferObj = Buffer.from(base64string, "base64");
// Decoding base64 into String
let string = bufferObj.toString("utf8");
// Printing the base64 decoded string
console.log("The Decoded base64 string is:", string);輸出
C:\home
ode>> node base64.js The Decoded base64 string is: TutorialsPoint
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP