2

I'm trying to push some data chunk read from my stream in a Buffer array, like this:

const chunks = [];
readableStream.on('data', chunks.push);

But then, chunks is empty.

The following works well but I'd like to find the difference between those two:

const chunks = [];
readableStream.on('data', (chunk) => chunks.push(chunk));

BTW, I'm using Node 6.2.2. Thank you

EDIT: I'm realizing there should be some context issue on the first line but explanations are welcome! Also, is there any recommandations/good practice on that?

NorTicUs
  • 718
  • 1
  • 10
  • 27

3 Answers3

0

In this line :

readableStream.on('data', (chunk) => chunks.push(chunk));

it is used a callback function that takes every item(chunk) and added it in chunks array, using push method.

The method is equivalent to :

const chunks = [];
readableStream.on('data',callback);
function callback(chunk){
     chunks.push(chunk);
}
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

The reason is that methods are a different language construct than functions. Array.prototype.push is a method. For what you're trying to do, you could do:

const chunks = [];
readableStream.on('data', chunks.push.bind(chunks));

bind here simply returns a new function object. The value of this within the function body is assigned to array. More info in this amazing answer on how this works in javascript (see the two sections about functions and function properties).

ljleb
  • 182
  • 1
  • 14
0
  1. [].push equal to Array.prototype.push, it losts the context. You should use bind function to set context.

  2. the on function just register your callback function. The 'data' event will be called async soon. So you can't get the value from array after on function.

It works for me:

const fs = require("fs");
const stream = fs.createReadStream("./demo.txt");
let r = [];
stream.on('data', r.push.bind(r));
console.info('empty array:', r);
setTimeout(()=>console.log('get result:', r), 1000);
Nick Ma
  • 26
  • 2