🐕
JavaScriptでの動画ダウンロード処理
ライブラリ
動画URL(S3 のURL等)に対して、ダウンロードする処理を実装したい時、FileSaver.js
を使うと便利でした。
しかし、README を見ればわかる通り、Chrome における Max Blob Size が 2GB となっており、2GB 以上のファイルもダウンロードしたかったので他のライブラリを探していると、StreamSaver.js
なるものがありました。
If you need to save really large files bigger than the blob's size limitation or don't have enough RAM, then have a look at the more advanced StreamSaver.js that can save data directly to the hard drive asynchronously with the power of the new streams API.
インストール
$ yarn add streamsaver @types/streamsaver
実装
今回は、TypeScript で書いています。
const downloadFile = async (url: string) => {
// クライアント側で読み込まないとエラーになる
const streamSaver = (await import('streamsaver')).default;
await fetch(url).then(async (response) => {
const blob = response.body;
const fileSize = Number(response.headers.get('content-length'));
const fileStream = streamSaver.createWriteStream(
file_name, // DL時のファイル名を指定できます
{ size: fileSize } // size を渡すと、DLにかかる時間を表示することができます
);
await blob?.pipeTo(fileStream);
});
};
Discussion