How to get the size of data in a Node JS Stream

Viewed 628

So I am using this npm library that returns SoundCloud music as a Stream. But after a while searching for an answer, I couldn't get an answer. I searched and discovered that it is impossible to get the full size of the data in a stream. But, is there a way for me to get the size of the data in that stream because I plan on using the size, to implement download progress in my app. Thanks a lot in advance.

From the library docs:

const scdl = require('soundcloud-downloader').default
const fs = require('fs')

const SOUNDCLOUD_URL = 'https://soundcloud.com/askdjfhaklshf'
const CLIENT_ID = 'asdhkalshdkhsf'

scdl.download(SOUNDCLOUD_URL).then(stream => stream.pipe(fs.createWriteStream('audio.mp3')))

Everything seems to work perfectly, but I am not able to count the bytes available in the stream instance returned in the callback

1 Answers

Yes, if the API returns a Stream you can calculate the size yourself as you read it. You didn't specify which library you're using but if it returns a stream you can add up the size of it as chunks of data come in.

e.g. (adapted straight from the Node.js docs):

// get the stream from some API.
const readable = getReadableStreamSomehow();
let readBytes = 0;


readable.on('data', (chunk) => {
  console.log(`Received ${chunk.length} bytes of data.`);
  readBytes += chunk.length;
});

readable.on('end', () => {
  console.log('All done.');
});
Related