Skip to content

字节与流.js ​

查看原文件

js
/**
 * 标准字节与流对象由运行时提供。
 * ArrayBuffer 是原始内存,Uint8Array 是字节视图;底层正文通过二进制桥传递,不强制 Base64。
 */

/**
 * 字节示例。调用写法:
 *
 * const bytes = new TextEncoder().encode("Hello");
 * const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
 * const rawBuffer = bytes.buffer;
 * const slice = bytes.subarray(1, 3);
 *
 * TypedArray 切片有 byteOffset/byteLength,传入 SDK 时保留实际范围。
 * Android 的 UTF-8 编码与 UTF-8/UTF-16 解码由原生加速,接口不变。
 * 分块复用同一 decoder:decode(chunk, { stream: true });结尾 decode()。
 * encodeInto(text, destination) 返回 { read, written },分别为 UTF-16 单元数和字节数,
 * 不写入半个字符,也不会为了小目标缓冲区先复制整份字符串。
 * 原生路径仍遵守任务时间/内存预算;大 JSON 仍须分页或自行流式解析。
 */
const bytes = new Uint8Array([72, 101, 108, 108, 111]);

/**
 * 内存文件的元数据。File 不等于文件选择器,也不会自动读取手机某条路径。
 * 调用写法:
 *
 * const blob = new Blob([bytes], { type: "text/plain" });
 * const file = new File([blob], "hello.txt", {
 *     type: "text/plain",
 *     lastModified: 0,
 * });
 *
 * await file.text();
 * await file.arrayBuffer();
 * file.stream();
 * file.slice(0, 5);
 */
const fileMetadata = {
    name: "hello.txt", // File 字段,Blob 没有 name/lastModified。
    type: "text/plain",
    size: 5, // 字节数,不是字符数。
    lastModified: 0,
};

/**
 * 表单与地址调用写法:
 *
 * const form = new FormData();
 * form.append("title", "示例");
 * form.append("attachment", file, file.name);
 * const response = await fetch(url,{method:"POST",body:form});
 * // 消费后关闭 response;不要手工写 multipart boundary。
 *
 * form.get("title");
 * form.getAll("attachment");
 * form.has("title");
 * form.set("title", "新名称");
 * form.delete("title");
 * form.entries();
 *
 * const query = new URLSearchParams([["tag", "小说"], ["tag", "完结"]]);
 * const url = new URL("/items", "https://example.invalid/");
 * url.search = query.toString();
 * const headers = new Headers({ Accept: "application/json" });
 * headers.set("X-Example", "1");
 */

/**
 * ReadableStream 读取的返回数据。调用写法:
 *
 * const reader = response.body.getReader(); // 先确认 body 非 null。
 * try {
 *     while (true) {
 *         const { value, done } = await reader.read();
 *         if (done) break;
 *         // await 处理当前 value,不必先拼接整个响应。
 *     }
 * } finally {
 *     reader.releaseLock();
 *     await response.body?.cancel();
 * }
 */
const streamReadResult = {
    done: false,
    value: bytes, // Uint8Array;读完后 done=true,value 不再提供有效数据块。
};

/**
 * 三种流与上传调用写法:
 *
 * const source = new ReadableStream({
 *     pull(controller) {
 *         controller.enqueue(new Uint8Array([1, 2, 3]));
 *         controller.close();
 *     },
 *     cancel(reason) {
 *         // 释放自己的生产者资源。
 *     },
 * });
 *
 * const response = await fetch(url,{method:"POST",body:source,duplex:"half"});
 * // 消费后关闭 response;一次性流不保证可以重放重试。
 *
 * const transform = new TransformStream({
 *     transform(chunk, controller) {
 *         controller.enqueue(chunk);
 *     },
 * });
 * const sink = new WritableStream({
 *     async write(chunk) {
 *         // 消费这个块。
 *     },
 * });
 * await anotherSource.pipeThrough(transform).pipeTo(sink);
 *
 * pipeTo 自动传播背压;同一条已经锁定/消费的流不要再交给另一消费者。
 */

/**
 * 取消调用写法:
 *
 * const controller = new AbortController();
 * const signal = AbortSignal.any([
 *     controller.signal,
 *     AbortSignal.timeout(10000),
 * ]);
 * const request = fetch(url,{signal});
 * controller.abort(); // 如用户主动取消。
 *
 * fetch 取消使用 signal.reason;宿主扩展的异常可用 isAbortError/getErrorCode 判断。
 * Event/EventTarget/DOMException 等基础对象也由运行时提供。
 */

// TextEncoder.encode/encodeInto 使用 UTF-8;后者返回 {read, written},不会写入半个字符。
// TextDecoder 支持流式解码及既有字符集;网络请求使用 fetch,会话与下载使用 http 扩展。

/** 标准编码/压缩转换流,背压、错误与取消连接上下游。
 * const text = source.pipeThrough(new TextDecoderStream("gb18030", { fatal: true }));
 * const bytes = text.pipeThrough(new TextEncoderStream()); // 标准UTF-8,跨块代理项保留。
 * const compressed = bytes.pipeThrough(new CompressionStream("brotli"));
 * const decoded = compressed.pipeThrough(new DecompressionStream("brotli"));
 * await decoded.pipeTo(destination.writable(), { signal });
 * format还包括gzip/deflate/deflate-raw;每块复制输入,64KiB处理,不用JS聚合整包。
 * 标准非法数据以TypeError拒绝;native分配预算和128MiB累计解压输出保护独立于背压。
 */