在 JavaScript 中将字符串转换为 ReadableStream

问题描述 投票:0回答:1

如何将字符串转换为 ReadableStream(不是 NodeJS 流)。

javascript browser stream
1个回答
-1
投票

将字符串转换为 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())

或通过

Blob.stream()

进行在线解决方案
const byteStream = new Blob([ str ], {type: 'text/plain'}).stream();
© www.soinside.com 2019 - 2024. All rights reserved.