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

strm-js

v1.1.1

Published

[![npm version](https://img.shields.io/npm/v/strm-js.svg)](https://www.npmjs.com/package/strm-js) [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

Readme

GT-Streaming JavaScript API 库

npm version license: MIT

GT-Streaming 流媒体服务的 JavaScript 客户端 SDK,提供 HTTP API 与 WebSocket API 两套接口,以及 FLV / HLS 播放器封装、常量与数据结构定义。

目录

特性

  • 双 API 入口StrmWsApi(WebSocket,适合实时流与推送通知)与 StrmHttpApi(REST,适合管理、查询、上传)
  • 播放器封装:支持 FLV(mpegts.js)与 HLS(hls.js / Safari 原生)
  • 流保活管理:内置 KeepAliveManager,支持服务端 Auto KeepAlive 特性
  • TypeScript 支持:自带类型声明,无需额外安装 @types
  • 工具模块:日期时间(dt-utils)、SIM 号校验(misc-utils)、日志(logger)等

安装

npm install strm-js

或使用 pnpm:

pnpm add strm-js

快速开始

以下示例演示通过 WebSocket 打开实时流并播放(需页面中已有 <video> 元素):

import {
    ApiReply,
    FlvPlayerWrapper,
    GnssLoginResult,
    GnssOpenLiveParams,
    GnssOpenStrmResult,
    PlayerContainer,
    PlayerWrapper,
    StrmConsts,
    StrmNotif,
    StrmWsApi,
    StrmWsApiConfig,
} from 'strm-js';

const videoEl = document.querySelector('video')!;
let player: FlvPlayerWrapper | null = null;
let reqId: string | undefined;
let openStrmResult: GnssOpenStrmResult | undefined;

const config = new StrmWsApiConfig();
config.wsApiUrl = 'wss://example.com:7012/ws2/v1/';
const api = new StrmWsApi(config);

api.addStrmNotifListener(onStrmNotif);

api.login('username', 'password')
    .then(() => openLive())
    .catch((err) => console.error('登录失败', err));

function openLive() {
    const params = new GnssOpenLiveParams();
    params.simNo = '13800138000';
    params.channel = 1;
    params.proto = StrmConsts.PROTO__FLV;
    params.async = true;

    api.liveOpen(params)
        .then((reply: ApiReply<GnssOpenStrmResult>) => {
            openStrmResult = reply.data![0];
            reqId = openStrmResult.reqId;
            if (openStrmResult.ready && !player) {
                createPlayerAndLoad(openStrmResult);
            }
        })
        .catch((err) => console.error('打开实时流失败', err));
}

function onStrmNotif(notif: StrmNotif) {
    if (notif.act === StrmNotif.ACT__strmReady && !player) {
        createPlayerAndLoad(notif);
    }
}

function createPlayerAndLoad(result: GnssOpenStrmResult | StrmNotif) {
    const container = new PlayerContainer(
        () => 'demo',
        () => !!openStrmResult,
        (err) => console.error('播放错误', err),
        () => console.debug('开始播放'),
        () => console.debug('播放结束'),
    );
    player = new FlvPlayerWrapper(container, videoEl, PlayerWrapper.MEDIA_TYP__AV, result.playUrl!);
    player.load();
}

function stop() {
    player?.stop();
    player = null;
    if (api.loggedIn && reqId) {
        api.releaseStrmReq(reqId);
        reqId = undefined;
    }
}

模块概览

| 模块 | 主要导出 | 用途 | |------|----------|------| | strm-ws-api | StrmWsApi, StrmWsApiConfig | WebSocket 实时流、媒体状态推送 | | strm-http-api | StrmHttpApi, StrmHttpApiConfig | HTTP REST 接口(登录、查询、上传等) | | strm-api | StrmApi, KeepAliveManager, StrmEvents | 两套 API 的公共基类与流保活 | | gnss-types | StrmConsts, StrmNotif, GnssOpenLiveParams, … | 常量、请求/响应结构体 | | player | PlayerWrapper, FlvPlayerWrapper, HlsJsPlayerWrapper, … | FLV / HLS 播放器封装 | | dt-utils | localDT, fmtConvenient, … | 日期时间格式化与换算 | | misc-utils | isValidSimNo, ordinalStr, … | 通用工具函数 | | logger | Logger, LogLevels | 日志级别控制 |

何时选用哪种 API?

  • StrmWsApi:需要实时音视频播放,并接收 StrmNotif 媒体状态推送(如流就绪、指令下发结果)
  • StrmHttpApi:仅需 REST 调用(日志查询、文件上传、巡检任务、服务端管理等),或无法使用 WebSocket 的场景
  • 两者均继承自 StrmApiliveOpenreplayOpenreleaseStrmReq 等流媒体接口签名一致

引入方式

ESM(推荐)

import { StrmWsApi, StrmHttpApi } from 'strm-js';

CommonJS

const { StrmWsApi, StrmHttpApi } = require('strm-js');

CDN(UMD)

<video id="player" controls></video>
<script src="https://unpkg.com/strm-js/dist/index.umd.js"></script>
<script>
  const { StrmWsApi, StrmWsApiConfig } = GnssJs;
  // ...
</script>

也可通过 jsDelivr 引入。

运行时依赖(axios、hls.js、mpegts.js 等)已打包进发布产物,使用者无需单独安装。

StrmWsApi 用法

StrmWsApi 是 WebSocket API 的入口类,适合实时流播放与媒体状态通知。

登录

import { GnssLoginResult, StrmWsApi, StrmWsApiConfig } from 'strm-js';

const config = new StrmWsApiConfig();
config.wsApiUrl = 'wss://example.com:7012/ws2/v1/'; // 必要参数
config.logLevel = 'debug'; // 可选,设置 WebSocket 通信日志级别

const strmWsApi = new StrmWsApi(config);
strmWsApi.addStrmNotifListener(onStrmNotif);

strmWsApi.login(username, password)
    .then((_: GnssLoginResult) => {
        console.debug('登录成功');
    })
    .catch((err) => {
        console.error('登录时遇到错误:' + err.toString());
    });

媒体状态变更通知

简单场景下,可只处理 StrmNotif.ACT__strmReady 通知。收到此通知后,创建播放器并开始播放:

import { StrmNotif } from 'strm-js';

function onStrmNotif(strmNotif: StrmNotif) {
    switch (strmNotif.act) {
        case StrmNotif.ACT__strmReady:
            if (strmNotif.simNo === simNo && strmNotif.chan === channel) {
                console.debug(`流已经准备好:${strmNotif.simNo}/${strmNotif.chan}`);
                if (!player) {
                    createPlayerAndLoad(strmNotif);
                }
            }
            break;

        case StrmNotif.ACT__cmdSent:
            console.debug(`指令已经下发:${strmNotif.simNo}/${strmNotif.chan}`);
            break;

        case StrmNotif.ACT__cmdFailed:
            console.debug(`指令失败:${strmNotif.simNo}/${strmNotif.chan}`);
            break;
    }
}

打开实时音视频

import {
    ApiReply,
    GnssOpenLiveParams,
    GnssOpenStrmResult,
    StrmConsts,
} from 'strm-js';

const params = new GnssOpenLiveParams();
params.simNo = simNo;
params.channel = channel;
params.dataType = selectedDataType;
params.codeStream = selectedCodeStrm;
params.async = true;
params.proto = StrmConsts.PROTO__FLV;

strmWsApi.liveOpen(params)
    .then((reply: ApiReply<GnssOpenStrmResult>) => {
        openStrmResult = reply.data![0];
        reqId = openStrmResult.reqId;

        // ready == true 表示流已就绪,可直接播放;否则等待 ACT__strmReady 通知
        if (openStrmResult.ready && !player) {
            createPlayerAndLoad(openStrmResult);
        }
    })
    .catch((err) => {
        console.error(`打开实时音视频失败:${err.toString()}`);
    });

打开远程录像回放

回放接口与实时流类似,使用 GnssOpenReplayParamsreplayOpen()

import {
    ApiReply,
    GnssOpenReplayParams,
    GnssOpenStrmResult,
    StrmConsts,
} from 'strm-js';

const params = new GnssOpenReplayParams();
params.simNo = simNo;
params.channel = channel;
params.startTime = '2026-07-01T08:00:00';
params.endTime = '2026-07-01T09:00:00';
params.proto = StrmConsts.PROTO__FLV;

strmWsApi.replayOpen(params)
    .then((reply: ApiReply<GnssOpenStrmResult>) => {
        openStrmResult = reply.data![0];
        reqId = openStrmResult.reqId;
        if (openStrmResult.ready && !player) {
            createPlayerAndLoad(openStrmResult);
        }
    })
    .catch((err) => console.error(`打开回放失败:${err.toString()}`));

关闭媒体流

function stop() {
    if (player) {
        player.stop();
        player = null;
    }

    if (strmWsApi?.loggedIn && reqId) {
        strmWsApi.releaseStrmReq(reqId);
        reqId = undefined;
    }

    console.debug('媒体流已经关闭');
}

StrmHttpApi 用法

StrmHttpApi 是 HTTP REST API 的入口类。构造时传入 API 地址与凭据,登录后调用各类 REST 接口。

构造与登录

import { StrmHttpApi, StrmHttpApiConfig } from 'strm-js';

const config = new StrmHttpApiConfig(
    'https://example.com:7012',  // API 根地址,库会自动补全 /v1/ 后缀
    'username',
    'password',
);
config.keepAliveIntvSeconds = 20; // 可选,流保活间隔(秒)

const api = new StrmHttpApi(config);

api.login()
    .then(() => {
        console.debug('HTTP 登录成功');
    })
    .catch((err) => {
        console.error('登录失败', err);
    });

调用流媒体接口

StrmHttpApiStrmWsApi 共享 StrmApi 基类,liveOpenreplayOpenreleaseStrmReq 等接口用法相同。区别在于 HTTP 版不会收到 WebSocket 推送,需自行轮询或结合 WS 使用。

典型 REST 场景

HTTP API 适用于以下场景(具体方法请参阅 TypeScript 类型声明或详细文档):

  • 媒体日志、通信日志查询
  • 音视频文件上传(reqAvUpload2
  • ADAS 附件任务管理
  • 视频巡检任务
  • 服务端状态查询

流保活 KeepAliveManager

打开实时流或回放后,媒体服务端的流请求需要定期保活,否则会被自动释放。

  • 调用 liveOpen() / replayOpen() 成功后,KeepAliveManager 会自动注册 reqId
  • 默认情况下,客户端每隔约 20 秒调用 /strm/keep 接口
  • 调用 releaseStrmReq() 后,对应 reqId 从保活列表中移除

服务端 Auto KeepAlive

自 v1.1.0 起,若服务端启用了自动流保活特性(StreamingFeatures.FEATURE__AUTO_KEEP_ALIVE),登录成功后库会自动检测并设置 ServerSideAutoKeepAlive,不再发起客户端周期性 keep 调用:

// 登录成功后自动处理,通常无需手动设置:
// api.keepAliveManager.ServerSideAutoKeepAlive = true

// 如需手动覆盖:
api.keepAliveManager.ServerSideAutoKeepAlive = true;

播放器用法

库内提供 FLV 与 HLS 两种协议的播放器封装。使用前需构造 PlayerContainer 回调对象:

import { PlayerContainer } from 'strm-js';

const playerContainer = new PlayerContainer(
    () => 'test',                          // 播放器 ID,多播放器场景用于区分
    () => !!openStrmResult,                // 是否仍在请求/播放中
    (err: string) => console.error(err),   // 播放错误
    () => console.debug('开始播放'),        // 开始播放
    () => console.debug('播放器已关闭'),    // 播放结束
);

播放器选型

| 协议 | 推荐类 | 能力检测 | |------|--------|----------| | FLV | FlvPlayerWrapper | flvJsSupported | | HLS(MSE) | HlsJsPlayerWrapper | hlsJsSupported | | HLS(Safari 原生) | HlsNativePlayer | supportNativeHLS() |

v1.1.1 修正了 supportNativeHLS() 在 Chrome 中误返回 true 的问题。非 Safari 浏览器应优先使用 HlsJsPlayerWrapper

直接创建

import { FlvPlayerWrapper, PlayerWrapper } from 'strm-js';

const player = new FlvPlayerWrapper(
    playerContainer,
    videoElmt,
    PlayerWrapper.MEDIA_TYP__AV,
    openStrmResult.playUrl,
);
player.load();

工厂方法(自动选择 FLV / HLS 实现)

import { PlayerWrapper, StrmConsts } from 'strm-js';

const player = PlayerWrapper.createPlayer(
    playerContainer,
    videoElmt,
    StrmConsts.PROTO__FLV,   // 或 StrmConsts.PROTO__HLS
    mediaNotif.mediaTyp!,
    openStrmResult.playUrl,
);
player.load();

错误处理与日志

ApiReply 与 ApiException

接口调用返回 ApiReply<T>,业务数据在 reply.data 数组中。发生业务错误时抛出 ApiException(含 errCode 属性):

import { ApiException } from 'strm-js';

api.liveOpen(params)
    .catch((err) => {
        if (err instanceof ApiException) {
            console.error(`错误码 ${err.errCode}: ${err.message}`);
        } else {
            console.error(err);
        }
    });

日志级别

WebSocket API 可通过 StrmWsApiConfig.logLevel 设置通信日志。也可独立使用 Logger

import { Logger, LogLevels } from 'strm-js';

const logger = new Logger(LogLevels.DEBUG);
logger.debug('调试信息');

兼容性

  • 浏览器:Chrome、Firefox、Safari、Edge 等现代浏览器
  • 运行环境:浏览器端(需 windowdocument;播放器需 <video> 元素)
  • TypeScript:>= 4.x,库自带 .d.ts 类型声明
  • 协议:FLV 依赖 MSE(mpegts.js);HLS 在 Safari 可用原生播放,其他浏览器通过 hls.js

更新日志

v1.1.1 (2026-07-05)

  • 修正 supportNativeHLS() 在 Chrome 浏览器中返回 true 的 BUG

v1.1.0 (2026-02-17)

  • 增加 StreamingFeatures 媒体服务特性定义类
  • 支持服务端 Auto KeepAlive 特性
  • 登录接口增加 baseOn 属性
  • hls.js 依赖升级到 1.6.16

查看完整更新日志

详细文档

请参阅 GT-Streaming 官方文档:

https://lucendar.com/docs/strm-api-4/ws2-api/ws2-intro

License

MIT