@cajuncodemonkey/json-streamify

中文文档
2.0.1发布于 2025/07/20MITTypeScriptESM + CJS零依赖近 30 天下载 2.3万

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

中文使用文档
文档目录20 节
  1. 目录
  2. 为什么Json会流?
  3. 关键特性
  4. 安装
  5. API 密码
  6. jsonStreamify(value, replacer?, space?)
  7. 兼容性
  8. 快速启动
  9. 服务器收到什么
  10. 演示
  11. 处理流线
  12. 使用网络标准可读结构
  13. 将节点.js流转换为可读结构
  14. 从数据创建可读结构
  15. 额外水电费
  16. streamToString(stream) 工具
  17. createStreamFromFile(filePath) 工具
  18. 常用案例
  19. 捐款
  20. 许可证

json -- -- 流化

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

目录

为什么Json会流?

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

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

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

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

关键特性

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

安装

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(中文(简体) )

快速启动

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

服务器收到什么

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

这个 ReadableStream 被自动转换为Base64!

演示

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

npm run demo

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

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

见 实例/README.md 用于详细的演示文档.

处理流线

使用网络标准可读结构

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

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内建流,将其转换为可读结构:

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

从数据创建可读结构

// 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) 工具

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) 工具

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 测试 - 在测试套间上传模拟文件

捐款

有兴趣捐款吗? 见 捐款额 用于开发设置,测试,代码质量标准和出版指南.

许可证

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

版本与发布记录

@cajuncodemonkey/json-streamify 共发布 4 个版本,首次发布于 2025/07/20;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.0.1latest2025/07/201.3 年前
2.0.02025/07/201.3 年前
1.0.12025/07/201.3 年前
1.0.02025/07/201.3 年前

关于 @cajuncodemonkey/json-streamify 的常见问题

@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 和提交记录判断。