Skip to content

Commit

Permalink
chore: fixed utils/downloadFile function using stream
Browse files Browse the repository at this point in the history
  • Loading branch information
l0r1s committed Apr 25, 2023
1 parent ea784f5 commit c0da81a
Showing 1 changed file with 7 additions and 15 deletions.
22 changes: 7 additions & 15 deletions javascript/packages/utils/src/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import dns from "dns";
import fs from "fs";
import { AddressInfo, createServer } from "net";
import os from "os";
import { Readable } from "stream";
import { finished } from "stream/promises";
import { ReadableStream } from "stream/web";
import { decorators } from "./colors";

export async function getRandomPort(): Promise<number> {
Expand Down Expand Up @@ -34,21 +37,10 @@ export async function getHostIp(): Promise<string> {

export async function downloadFile(url: string, dest: string): Promise<void> {
try {
await new Promise<void>(async (resolve) => {
const response = await fetch(url);
const reader = response.body?.getReader();
const writer = fs.createWriteStream(dest);
let i = true;
while (i) {
const read = await reader?.read();
if (read?.done) {
writer.close();
i = false;
resolve();
}
writer.write(read?.value);
}
});
const { body } = await fetch(url);
const writable = fs.createWriteStream(dest);
const readable = Readable.fromWeb(body as ReadableStream);
await finished(readable.pipe(writable));
} catch (err) {
console.log(
`\n ${decorators.red("Unexpected error: ")} \t ${decorators.bright(
Expand Down

0 comments on commit c0da81a

Please sign in to comment.