# @cajuncodemonkey/json-streamify 中文文档

规范地址：https://npmcn.com/package/%40cajuncodemonkey/json-streamify/

版本：2\.0\.1
npm 元数据更新时间：2025-07-19T19:57:28.906Z
中文译文更新时间：2026-11-08T23:40:38.994Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40cajuncodemonkey/json-streamify
原文对照：https://npmcn.com/package/%40cajuncodemonkey/json-streamify/?lang=original

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：112 kB，58 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=18\.0\.0
- 运行依赖：0 个
- 首次发布：2025-07-19T16:03:12.569Z
- 最新版本发布：2025-07-19T19:57:28.702Z
- 近 30 天下载量：22858（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：4（近 12 个月 0 个）

## 中文简介

就像JSON.stringify 但返回一个可读结构,其中包含有 Base64 编码的嵌入流

## 安装

```sh
npm install @cajuncodemonkey/json-streamify
```

也可以使用：`pnpm add @cajuncodemonkey/json-streamify`、`yarn add @cajuncodemonkey/json-streamify`、`bun add @cajuncodemonkey/json-streamify`

## README

# json -- -- 流化

一个流式JSON序列器,可以自动将嵌入式可读结构转换为 Base64.

## 目录

-   [为什么Json会流?](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-why-json-streamify)
-   [关键特性](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-key-features)
-   [安装](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-installation)
-   [API 密码](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-api)
-   [兼容性](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-compatibility)
-   [快速启动](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-quick-start)
-   [演示](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-demo)
-   [处理流线](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-working-with-streams)
-   [额外水电费](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-additional-utilities)
-   [常用案例](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-common-use-cases)
-   [捐款](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-contributing)
-   [许可证](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/#readme-license)

## 为什么Json会流?

在构建需要用二进制文件数据发送JSON的API时,您通常面临两个问题:

1.  **内存使用情况**: 将全部文件装入JSON编码的内存
2.  **编码复杂度**: 在 JSON 序列化前手动将文件转换到 Base64

`json-streamify` 以下列两种方法解决:

-   接受 `ReadableStream` 直接在 JSON 结构中的流
-   序列化时自动转换到 Base64
-   正在返回 a `ReadableStream` 用于内存高效的 HTTP 请求

## 关键特性

-   **滴入替换** 页:1 `JSON.stringify()` 有流支持
-   **自动 Base64 编码** 编号 `ReadableStream` 数据中的流
-   **内存效率** - 流文件而不是装入内存
-   **类型脚本支持** 带有完整类型定义
-   **双重模块支持** - 与通用JS和ES模块合作

## 安装

```sh
npm install @cajuncodemonkey/json-streamify
```

## API 密码

### `jsonStreamify(value, replacer?, space?)`

就是这样 `JSON.stringify()` 返回一个 `ReadableStream` 自动转换嵌入式 `ReadableStream` 溪流到 Base64.

**参数:**

-   `value` - 序列化值(可包含 `ReadableStream` 溪流)
-   `replacer` - 转换值的可选函数(与JSON.stringify相同)
-   `space` - 可选格式化参数(与JSON.stringify相同)

**回返情况:** `ReadableStream<string>` - 输出 JSON 字符串的流

#### `streamToString(stream)`

转换一个函数的工具 `ReadableStream` 到一个字符串.

**参数:**

-   `stream` - 那个 `ReadableStream` 转换

**回返情况:** `Promise<string>` - 保证能解决全部的字符串内容

#### `createStreamFromFile(filePath)`

创建一个 `ReadableStream` 从文件.

**参数:**

-   `filePath` - 要读取的文件的路径

**回返情况:** `ReadableStream<Uint8Array>` - 包含文件内容的流

## 兼容性

-   **节点.js**: 18.0.0 或更高(使用 Web Streams API)
-   **浏览器**: 有可读结构支持的现代浏览器
-   **德诺**: 全力支持网页标准流
-   **类型脚本**: 包括完整类型定义
-   **模块**: 支持两个共同JS(`require`)和ES模块(`import`(中文(简体) )

## 快速启动

```typescript
import { jsonStreamify, streamToString } from '@cajuncodemonkey/json-streamify';

// Your data with embedded file streams
const payload = {
  message: 'Upload request',
  file: new ReadableStream({
    start(controller) {
      controller.enqueue(new TextEncoder().encode('Hello, World!'));
      controller.close();
    },
  }),
  metadata: { filename: 'hello.txt' },
};

// Convert to JSON stream (file automatically becomes Base64)
const jsonStream = jsonStreamify(payload);

// Use directly with fetch - no manual Base64 conversion needed!
const response = await fetch('/api/upload', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: jsonStream,
  duplex: 'half', // Required for streaming bodies
} as RequestInit); // Type assertion needed for TypeScript compatibility

// Or with wretch for cleaner API calls
import wretch from 'wretch';

const result = await wretch('/api/upload')
  .headers({ 'Content-Type': 'application/json' })
  .body(jsonStream)
  .options({ duplex: 'half' })
  .post()
  .json();
```

### 服务器收到什么

```json
{
  "message": "Upload request",
  "file": "SGVsbG8sIFdvcmxkIQ==",
  "metadata": { "filename": "hello.txt" }
}
```

这个 `ReadableStream` 被自动转换为Base64!

## 演示

运行包含的演示, 以看到 json- sreamfy 与真实的网络 API 工作 :

```bash
npm run demo
```

这开始一个本地的Express服务器,接受 Base64-编码文件并显示:

-   在 JSON 内将可读流转换为 Base64
-   生成的 JSON 的 HTTP 传输
-   服务器端解码和文件重建
-   整个过程中元数据保存

见 [实例/README.md](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/examples/README.md) 用于详细的演示文档.

## 处理流线

### 使用网络标准可读结构

`json-streamify` 使用网络标准 `ReadableStream` API,使其兼容整个Node.js,浏览器,和Deno:

```typescript
import { jsonStreamify } from '@cajuncodemonkey/json-streamify';

// Create a ReadableStream from data
const dataStream = new ReadableStream({
  start(controller) {
    controller.enqueue(new TextEncoder().encode('Hello, World!'));
    controller.close();
  },
});

const payload = { attachment: dataStream };
const jsonStream = jsonStreamify(payload);
```

### 将节点.js流转换为可读结构

对于Node.js内建流,将其转换为可读结构:

```typescript
import { createReadStream } from 'fs';
import { Readable } from 'stream';

// Convert Node.js Readable to web ReadableStream
const nodeStream = createReadStream('./document.pdf');
const webStream = Readable.toWeb(nodeStream);

const payload = { attachment: webStream };
const jsonStream = jsonStreamify(payload);
```

### 从数据创建可读结构

```typescript
// From Uint8Array
const binaryStream = new ReadableStream({
  start(controller) {
    const data = new Uint8Array([72, 101, 108, 108, 111]); // "Hello"
    controller.enqueue(data);
    controller.close();
  },
});

// From string chunks
const textStream = new ReadableStream({
  start(controller) {
    const chunks = ['Hello', ' ', 'World', '!'];
    chunks.forEach(chunk =>
      controller.enqueue(new TextEncoder().encode(chunk))
    );
    controller.close();
  },
});
```

## 额外水电费

库还输出出两个对流处理有用的功能:

### `streamToString(stream)` 工具

```typescript
import { streamToString } from '@cajuncodemonkey/json-streamify';

const stream = new ReadableStream({
  start(controller) {
    controller.enqueue('Hello');
    controller.enqueue(' ');
    controller.enqueue('World');
    controller.close();
  },
});
const text = await streamToString(stream);
console.log(text); // "Hello World"
```

### `createStreamFromFile(filePath)` 工具

```typescript
import { createStreamFromFile } from '@cajuncodemonkey/json-streamify';

const fileStream = createStreamFromFile('./document.pdf');
// Use the stream in your JSON payload
const payload = { attachment: fileStream };
```

## 常用案例

-   **在 JSON API 中上传文件** - 作为JSON请求的一部分发送文件
-   **图QL 变异** - 在图QL变量中包含二进制数据
-   **带有附件的 Webhoks** - 随元数据一起发送文件
-   **微服务通信** - 通过JSON在服务之间传递文件
-   **API 测试** - 在测试套间上传模拟文件

## 捐款

有兴趣捐款吗? 见 [捐款额](https://npmcn.com/package/%40cajuncodemonkey/json-streamify/CONTRIBUTING.md) 用于开发设置,测试,代码质量标准和出版指南.

## 许可证

这个图书馆申请了麻省理工学院的执照. 随便你怎么用吧,你自己冒险 请随意复制/粘贴 使用 npm 软件包的代码.

## 常见问题

### @cajuncodemonkey/json-streamify 是什么？

就像JSON\.stringify 但返回一个可读结构,其中包含有 Base64 编码的嵌入流

### 如何安装 @cajuncodemonkey/json-streamify？

在项目目录运行 npm install @cajuncodemonkey/json-streamify，或使用 pnpm add / yarn add / bun add。

### @cajuncodemonkey/json-streamify 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @cajuncodemonkey/json-streamify 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @cajuncodemonkey/json-streamify 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @cajuncodemonkey/json-streamify 可以商用吗？

@cajuncodemonkey/json-streamify 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @cajuncodemonkey/json-streamify 的下载量有多少？

根据 npm 官方下载统计，@cajuncodemonkey/json-streamify 在 2026/10/09 – 2026/11/07 这 30 天内被下载 22,858 次，日均约 762 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @cajuncodemonkey/json-streamify 还在维护吗？

最新版本 2\.0\.1 发布于 2025/07/20（1\.3 年前）；至今共发布 4 个版本，其中过去 12 个月发布了 0 个；首次发布于 2025/07/20。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

