json -- -- 流化
一个流式JSON序列器,可以自动将嵌入式可读结构转换为 Base64.
目录
为什么Json会流?
在构建需要用二进制文件数据发送JSON的API时,您通常面临两个问题:
- 内存使用情况: 将全部文件装入JSON编码的内存
- 编码复杂度: 在 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 软件包的代码.