TS 第三方库来模拟Buffer.from()
时间: 2023-08-21 13:07:41 浏览: 45
在浏览器环境下,可以使用 `typedarray-to-buffer` 库来模拟 Node.js 中的 `Buffer.from()` 方法。首先需要安装该库:
```
npm install typedarray-to-buffer
```
然后在 TypeScript 代码中引入该库并使用,示例代码如下:
```typescript
import typedarrayToBuffer from 'typedarray-to-buffer';
const uint8Array = new Uint8Array([1, 2, 3, 4]);
const buffer = typedarrayToBuffer(uint8Array);
console.log(buffer);
```
输出结果与 Node.js 中相同:
```
<Buffer 01 02 03 04>
```
需要注意的是,该库只支持将 Uint8Array 转换成 Buffer 类型,如果需要转换其他类型的 TypedArray,可以使用其他第三方库,比如 `buffer`、`buffer-es6` 等。
相关问题
TS 第三方库或者官方库来模拟Buffer.from()
在浏览器环境下,可以使用 `typedarray-to-buffer` 或者 `base64-js` 库来模拟 Node.js 中的 `Buffer.from()` 方法。
- `typedarray-to-buffer`:用于将 TypedArray 转换成 Buffer 类型。
- `base64-js`:用于将 Base64 字符串转换成 Buffer 类型。
这两个库都可以通过 npm 安装,使用时需要先引入并初始化,示例代码如下:
```typescript
import * as typedarrayToBuffer from 'typedarray-to-buffer';
import * as base64js from 'base64-js';
// 初始化 typedarray-to-buffer 库
(window as any).Buffer = typedarrayToBuffer;
// 初始化 base64-js 库
(window as any).atob = base64js.atob;
(window as any).btoa = base64js.btoa;
// 使用 Buffer.from() 方法
const uint8Array = new Uint8Array([1, 2, 3, 4]);
const buffer1 = Buffer.from(uint8Array);
console.log(buffer1);
const base64String = 'AQIDBA==';
const buffer2 = Buffer.from(base64String, 'base64');
console.log(buffer2);
```
需要注意的是,在使用 `typedarray-to-buffer` 库时,需要将 `Buffer` 对象添加到全局对象 `window` 中,以便在 TypeScript 中可以使用该对象。在使用 `base64-js` 库时,需要将 `atob` 和 `btoa` 方法添加到全局对象中,以便在 TypeScript 中可以使用该方法。
TS里Buffer.from(str)
这是一个IT类问题。在 TypeScript 中,Buffer.from(str) 方法用于创建一个新的 Buffer 实例,其中包含给定的字符串 str 的二进制数据。该方法的返回值类型为 Buffer。需要注意的是,Buffer 是 Node.js 中用于处理二进制数据的类。因此,该方法只能在 Node.js 中使用,在浏览器端不可用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)