How to use the once function from readable-stream

Find comprehensive JavaScript readable-stream.once code examples handpicked from public code repositorys.

readable-stream.once registers a one-time event listener on a readable stream that will execute the given callback function once when the event is triggered.

7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);


  if (cb) {
    if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
  }


  state.ended = true;
  stream.writable = false;
fork icon2
star icon3
watch icon1

5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081


function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);
  if (cb) {
    if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  }
  state.ended = true;
  stream.writable = false;
}
fork icon0
star icon0
watch icon0

+ 2 other calls in file

How does readable-stream.once work?

readable-stream.once is a method that adds a one-time listener function for a specific event to a Readable stream, which will execute the listener function at most once the next time the event is triggered.

Ai Example

1
2
3
4
5
6
7
8
9
10
11
const { Readable } = require("stream");

const stream = new Readable({
  read() {},
});

stream.once("data", (chunk) => {
  console.log(`Received chunk: ${chunk}`);
});

stream.push("Hello, world!");

In this example, a new Readable stream is created that overrides the read method with an empty function, effectively creating a "push" stream. The once method is called on the stream with the event type data and a callback function that logs the received chunk to the console. Finally, a chunk is pushed into the stream by calling the push method with the string "Hello, world!". Since the once method was used, the callback function will only be called once with the first data event that is emitted by the stream.