node.js - Readable and writable streams unexpected behavior -


i run unexpected behavior regards fs.createreadstream , fs.createwritestream. hope can point out make wrong assumptions:

i create readable , writable stream this

let readablestream = fs.createreadstream('./lorem ipsum.doc'); let writablestream = fs.createwritestream('./output'); 

why, if send read stream write stream this

let data, chunk; readablestream .on('readable', () => {     while ((chunk=stream.read()) !== null) {         data+=chunk;     } }) .on('end', ()=>{     writablestream.write(data)     console.log("done"); }); 

i end discrepancy in output file:

output file discrepancy

while if stream this:

let data, chunk; readablestream .on('readable', () => {     while ((chunk=stream.read()) !== null) {         writablestream.write(chunk)     } }) .on('end', ()=>{     console.log("done"); }); 

all fine , expected:

expected output

i.e., in first example, when/where additional overhead in bytes added? why added? goes wrong?

thanks enlightening me!


note: aware of using pipe (which gives me correct output file), these examples understanding.

i guessing point in first demo, use 'data +=', converts binary stream character string, , wastes space. please try convert second demo too? ===>

var s=chunk;   writablestream.write(s); 

updated: correct way combine stream buffer comment:

var chunks = []; var size = 0; ...on('data', function(chunk){     chunks.push(chunk);     size += chunk.length; }) ...on('end', function(){     var buf = buffer.concat(chunks, size); // use buf write writestream     var str = iconv.decode(buf, 'utf8');   // use str console.log string, supports languages such asian }) 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -