Skip to content

doc: fix bug in stream doc unshift example#41944

Merged
aduh95 merged 1 commit intonodejs:masterfrom
meixg:stream-doc-meixg
Feb 15, 2022
Merged

doc: fix bug in stream doc unshift example#41944
aduh95 merged 1 commit intonodejs:masterfrom
meixg:stream-doc-meixg

Conversation

@meixg
Copy link
Copy Markdown
Member

@meixg meixg commented Feb 12, 2022

I guess the example should only retrieve the header part, but without return, it will keep running.

say we have a file with content:

header

body1

body2

body3


and with the example:

const { StringDecoder } = require('string_decoder');
const fs = require('fs');
const path = require('path');
function parseHeader(stream, callback) {
  stream.on('error', callback);
  stream.on('readable', onReadable);
  const decoder = new StringDecoder('utf8');
  let header = '';
  function onReadable() {
    let chunk;
    while (null !== (chunk = stream.read())) {
      const str = decoder.write(chunk);
      if (str.match(/\n\n/)) {
        // Found the header boundary.
        const split = str.split(/\n\n/);
        header += split.shift();
        const remaining = split.join('\n\n');
        const buf = Buffer.from(remaining, 'utf8');
        stream.removeListener('error', callback);
        // Remove the 'readable' listener before unshifting.
        stream.removeListener('readable', onReadable);
        if (buf.length)
          stream.unshift(buf);
        // Now the body of the message can be read from the stream.
        callback(null, header, stream);
        // return;
      } else {
        // Still reading the header.
        header += str;
      }
    }
  }
}

const fsStream = fs.createReadStream(path.resolve(__dirname, './sample'));
parseHeader(fsStream, (error, header, stream) => {
    console.log(error, header);
});

output:

null header
null headerbody1
null headerbody1body2
null headerbody1body2body3

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commit-queue-failed An error occurred while landing this pull request using GitHub Actions. doc Issues and PRs related to the documentations. stream Issues and PRs related to the stream subsystem.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants