Stream
Utilities for working with Stream.
Example Usage
// express handler example
import express from 'express';
import { openai } from 'ai/openai';
import { convertWebStreamToNodeStream } from './stream';
const app = express();
app.get('/stream', async (req, res) => {
// ai sdk stream
const aiStream = openai.createChatCompletion({ mode: 'XXX', stream: true });
// convert WebStream to Node ReadableStream
const nodeRs = await convertWebStreamToNodeStream(aiStream.body);
// ...
})
// vitest example
import { it, expect } from 'vitest';
import { readWebStreamIntoString } from './stream';
it('should convert WebStream to string', async () => {
// ai sdk stream
const aiStream = openai.createChatCompletion({ mode: 'XXX', stream: true });
// convert the stream to a single string
const resultString = await readWebStreamIntoString(aiStream.body);
// check the result
expect(resultString).toBe('hello');
})
Dependencies
No dependencies
Auto Install
npx shadcn@latest add https://shadcn-registry-ts.vercel.app/r/util-stream.json
Manual Install
stream.ts
/**
* Source: http://localhost:3000
*/
import { Readable } from 'stream';
/**
* Convert a `Web ReadableSream` to a `Node ReadableStream`
*/
export const convertWebStreamToNodeStream = async (webStream: ReadableStream<Uint8Array>) => {
const reader = webStream.getReader();
return new Readable({
async read() {
const { done, value } = await reader.read();
if (done) {
this.push(null); // Chiude lo stream
} else {
this.push(value); // Passa il chunk
}
},
});
};
/**
* Read a `Web ReadableSream` into a string
*/
export const readWebStreamIntoString = async (webStream: ReadableStream) => {
let output = "";
const nodeRs = await convertWebStreamToNodeStream(webStream);
for await (const chunk of nodeRs) {
output += chunk;
}
return output;
};
Test
No test
Command Palette
Search for a command to run...