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

时间:2019-07-09 12:16:30

标签: typescript express tobase64string

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

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

我们通常使用

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

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

3 个答案:

答案 0 :(得分:7)

在节点打字稿中:

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

答案 1 :(得分:0)

请使用bota编码字符串

console.log(btoa("abc")); // YWJj

用于atob解码相同的字符串

console.log(atob("YWJj")); // abc

答案 2 :(得分:0)

如果在前端使用了window.btoa(fileData)

注意:在收到zerkms的反馈并阅读了包装代码之后,看来您可以手动进行操作。但是我不得不两次运行它。
我也在尝试解码大图像。

然后在nodejs服务器上,您可以直接使用Buffer:

const b64 = "SGVsbG8sIFdvcmxkIQ==";
const fileDataProcessed = Buffer.from(b64, 'base64').toString('binary')
const decodedData = Buffer(fileDataProcessed, 'base64')

// This is the code that you can now upload to your s3 bucket, or somewhere else.
console.log(decodedData);
相关问题