簡體   English   中英

如何獲取 Node JS Stream 中的數據大小

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

所以我正在使用這個npm 庫,它將 SoundCloud 音樂作為Stream返回。 但在尋找答案一段時間后,我無法得到答案。 我搜索並發現不可能在 stream 中獲得完整大小的數據。 但是,有沒有辦法讓我獲得 stream 中的數據大小,因為我計划使用該大小來實現我的應用程序中的下載進度。 提前非常感謝。

從圖書館文檔:

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')))

一切似乎都很完美,但我無法計算回調中返回的stream實例中可用的字節數

是的,如果 API 返回 Stream,您可以在閱讀時自行計算大小。 您沒有指定您正在使用哪個庫,但如果它返回 stream 您可以在數據塊進入時將其大小相加。

例如(直接改編自 Node.js 文檔):

// 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.');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM