首页 > 解决方案 > 如何在打字稿快递服务器中将字符串解码/编码为base64

问题描述

我有一个用打字稿写的快递服务器。

作为atob()btoa()在浏览器上工作,在 Nodejs 上。

我们一般使用

Buffer.from("some-string").toString('base64')将字符串编码为base64。

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

标签: typescriptexpresstobase64string

解决方案


在节点打字稿中:

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)
});

推荐阅读