gpt4 book ai didi

typescript - 如何在TypeScript Express服务器中将字符串解码/编码为base64

转载 作者:行者123 更新时间:2023-12-03 16:07:44 25 4
gpt4 key购买 nike

我有一个用 typescript 写的 express 服务器。

由于atob()btoa()可在浏览器上以及Node.js上运行。

我们一般使用
Buffer.from("some-string").toString('base64')将字符串编码为base64。

但是,当我在TypeScript中编写代码时,这似乎不起作用。我需要一些帮助。

最佳答案

在节点 typescript 中:

const b64 = "SGVsbG8sIFdvcmxkIQ==";
const str = 'Hello, World!'

const decode = (str: string):string => Buffer.from(str, 'base64').toString('binary');
const encode = (str: string):string => Buffer.from(str, 'binary').toString('base64');

test('base64 decode', () => {
expect(decode(b64)).toEqual(str)
});

test('base64 decode', () => {
expect(encode(str)).toEqual(b64)
});

test('base64 encode/decode', () => {
expect(decode(encode(str))).toEqual(str)
});

关于typescript - 如何在TypeScript Express服务器中将字符串解码/编码为base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56952405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com