gpt4free-ts/utils/index.ts

43 行
1.3 KiB
TypeScript
Raw 通常表示 履歴

2023-05-04 22:32:21 +09:00
import es from 'event-stream';
import {PassThrough, Stream} from 'stream';
2023-05-05 19:36:27 +09:00
import * as crypto from 'crypto';
import {v4} from "uuid";
2023-05-04 22:32:21 +09:00
type eventFunc = (eventName: string, data: string) => void;
export function toEventCB(arr: Uint8Array, emit: eventFunc) {
const pt = new PassThrough();
pt.write(arr)
pt.pipe(es.split(/\r?\n\r?\n/)) //split stream to break on newlines
.pipe(es.map(async function (chunk: any, cb: Function) { //turn this async function into a stream
const [eventStr, dataStr] = (chunk as any).split(/\r?\n/)
const event = eventStr.replace(/event: /, '');
const data = dataStr.replace(/data: /, '');
emit(event, data);
cb(null, {data, event});
}))
}
export function toEventStream(arr: Uint8Array): Stream {
const pt = new PassThrough();
pt.write(arr)
return pt;
}
2023-05-05 19:36:27 +09:00
export function md5(str: string): string {
return crypto.createHash('md5').update(str).digest('hex');
}
export function randomStr(): string {
return v4().split('-').join('').slice(-6);
}
export function parseJSON(str: string, defaultObj: any): any | undefined {
try {
return JSON.parse(str)
} catch (e) {
2023-05-06 12:34:37 +09:00
console.error(str,e);
2023-05-05 19:36:27 +09:00
return defaultObj;
}
}