Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to ReadableStream in JavaScript

How to convert a string to ReadableStream (not NodeJS stream).

like image 557
Rex Pan Avatar asked Mar 27 '26 22:03

Rex Pan


1 Answers

To convert a string to ReadableStream

function stringToStream(str) {
    return new ReadableStream({
        start(controller) { // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultController
            controller.enqueue(str); 
            controller.close();
        },
    })
}
const stringStream = stringToStream("some text");
// convert the string stream to byte using TextEncoderStream if you need to consume as byte like .pipeThrough(new CompressionStream())
const byteStream = stringStream.pipeThrough(new TextEncoderStream())

Or oneline solution by Blob.stream()

const byteStream = new Blob([ str ], {type: 'text/plain'}).stream();
like image 58
Rex Pan Avatar answered Mar 29 '26 11:03

Rex Pan