npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sparta-utils/stream-request

v1.0.6

Published

用于流式传输HTTP请求的轻量级实用程序

Readme

@sparta-utils/stream-request

一个支持 流式响应(如 SSE、AI 多轮对话等)的轻量级请求工具库,支持逐段处理、超时、取消、自动 JSON 行解析,并在请求结束时返回完整响应信息。


✨ 特性

  • 流式逐段处理响应数据(边下边处理)
  • 自动 JSON 行解析(可选)
  • ✅ 支持 请求中断(AbortSignal)、超时控制
  • 请求完成时返回完整响应内容和 HTTP 元信息
  • ✅ 完全自定义请求头,支持所有 HTTP 方法
  • ✅ 支持上传 FormData

📦 安装

npm install @sparta-utils/stream-request
# 或
yarn add @sparta-utils/stream-request

🚀 快速上手

import { streamRequest } from '@sparta-utils/stream-request';

streamRequest('https://your-api.com/stream', {
  method: 'POST',
  body: { prompt: '你好 AI' },
  headers: {
    Authorization: 'Bearer your-token',
    'Custom-Header': '自定义内容'
  },
  autoParseJSON: true, // 自动解析每行 JSON
  onMessage: (text) => {
    console.log('收到分段数据:', text);
  },
  onDone: (fullText, responseInfo) => {
    console.log('✅ 请求完成,完整内容:', fullText);
    console.log('HTTP 元信息:', responseInfo);
  },
  onError: (err) => {
    console.error('❌ 出错:', err);
  },
  timeout: 10000 // 10 秒超时
});

📚 参数说明

| 参数名 | 类型 | 说明 | | ----------------- | ------------------------ | ---- | | url | string | 请求地址 | | method | 'GET' \| 'POST' \| ... | 请求方法,默认 GET | | headers | Record<string, string> | 自定义请求头 | | body | object \| FormData | 请求体(会自动判断是否 FormData) | | onMessage | (text: string) => void | 流式分段回调(每接收到一段数据调用一次) | | onDone | (fullText: string, responseInfo: ResponseInfo) => void | 请求结束回调,返回完整文本和 HTTP 元信息 | | onError | (error: any) => void | 错误回调 | | autoParseJSON | boolean | 自动按行解析 JSON(解析失败会保留原文) | | decoderEncoding | string | 编码,默认 utf-8 | | timeout | number(毫秒) | 超时时间,到达后自动中断 | | signal | AbortSignal | 外部中断信号对象 | | lineSeparator | string | 流分段分隔符,默认 \n | | onProgress | (bytes: number) => void| 已接收字节数实时回调 | | onRawChunk | (chunk: Uint8Array) => void | 原始二进制块回调 |

ResponseInfo 结构

interface ResponseInfo {
  status: number
  statusText: string
  headers: Record<string, string>
  url: string
  parsedBody?: any // 当 autoParseJSON=true 且解析成功时存在
}

⏹ 中断请求

const controller = new AbortController();

streamRequest('/api/stream', {
  signal: controller.signal,
  onMessage: console.log,
  onError: (err) => console.error(err)
});

// 3 秒后中断请求
setTimeout(() => {
  controller.abort();
}, 3000);

🌍 常用 HTTP 方法示例

// PUT 更新
streamRequest('/api/item/123', {
  method: 'PUT',
  body: { name: '新名称' },
  headers: { Authorization: 'Bearer xxx' },
  onMessage: (text) => console.log('PUT 响应片段:', text)
});

// DELETE 删除
streamRequest('/api/item/123', {
  method: 'DELETE',
  headers: { Authorization: 'Bearer xxx' },
  onMessage: (text) => console.log('DELETE 响应片段:', text)
});

🔍 进阶:文件上传 + 流式处理

const formData = new FormData();
formData.append('file', fileInput.files[0]);

streamRequest('/api/upload', {
  method: 'POST',
  body: formData,
  onProgress: (bytes) => {
    console.log('已接收字节:', bytes);
  },
  onMessage: (text) => {
    console.log('上传进度:', text);
  },
  onDone: (fullText) => {
    console.log('上传完成:', fullText);
  }
});

⚠️ 注意事项

  1. 超时外部中断 会触发 onError,不会重试。
  2. autoParseJSON 会尝试按行解析 JSON,适合 SSE/AI 流;如果数据不是标准 JSON 行,请设为 false
  3. 流模式下的 fullText所有片段拼接结果,如果后端最后会返回完整 JSON,可以在 onDone 里解析。

📄 许可证

MIT License © 2025