3

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

Noah
  • 567
  • 5
  • 21

1 Answers1

1

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.');
});
Pure Function
  • 2,129
  • 1
  • 22
  • 31
  • Thank you for your reply. I also thought of this, but how would I get the **full size** of the file, then count the size of the chunk of data being received – Noah Jan 31 '22 at 04:24
  • 1
    Actually soundcloud does not return the content-length in http header , had it been the case then you could have used that.. for now what has been responded above looks like the best that you can do... – Soumen Mukherjee Jan 31 '22 at 04:46
  • Yes Sorry @Noah I thought you realised already that it was impossible to get the file size from SoundCloud. (you mention that in your question). Soundcloud does not expose this info on headers or on API as far as I can tell. – Pure Function Jan 31 '22 at 19:44