Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Cloudflare Docs
Log in

TheNode.js streams API is the original API for working with streaming data in JavaScript, predating theWHATWG ReadableStream standard. A stream is an abstract interface for working with streaming data in Node.js. Streams can be readable, writable, or both. All streams are instances ofEventEmitter.

Where possible, you should use theWHATWG standard "Web Streams" API, which issupported in Workers.

JavaScript
import{Readable,Transform} from"node:stream";
import{text} from"node:stream/consumers";
import{pipeline} from"node:stream/promises";
// A Node.js-style Transform that converts data to uppercase
// and appends a newline to the end of the output.
classMyTransformextendsTransform{
constructor(){
super({ encoding:"utf8"});
}
_transform(chunk,_,cb){
this.push(chunk.toString().toUpperCase());
cb();
}
_flush(cb){
this.push("\n");
cb();
}
}
exportdefault{
asyncfetch(){
constchunks= [
"hello ",
"from ",
"the ",
"wonderful ",
"world ",
"of ",
"node.js ",
"streams!",
];
functionnextChunk(readable){
readable.push(chunks.shift());
if (chunks.length===0)readable.push(null);
elsequeueMicrotask(()=>nextChunk(readable));
}
// A Node.js-style Readable that emits chunks from the
// array...
constreadable=newReadable({
encoding:"utf8",
read(){
nextChunk(readable);
},
});
consttransform=newMyTransform();
awaitpipeline(readable,transform);
returnnewResponse(awaittext(transform));
},
};

Refer to theNode.js documentation forstream for more information.


[8]
ページ先頭

©2009-2026 Movatter.jp