vscode: switched to stream.pipeline with .on(close) workaround
This commit is contained in:
@@ -1,8 +1,12 @@
|
|||||||
import fetch from "node-fetch";
|
import fetch from "node-fetch";
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
|
import * as stream from "stream";
|
||||||
|
import * as util from "util";
|
||||||
import { strict as assert } from "assert";
|
import { strict as assert } from "assert";
|
||||||
import { NestedError } from "ts-nested-error";
|
import { NestedError } from "ts-nested-error";
|
||||||
|
|
||||||
|
const pipeline = util.promisify(stream.pipeline);
|
||||||
|
|
||||||
class DownloadFileError extends NestedError {}
|
class DownloadFileError extends NestedError {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,25 +33,19 @@ export async function downloadFile(
|
|||||||
const totalBytes = Number(res.headers.get('content-length'));
|
const totalBytes = Number(res.headers.get('content-length'));
|
||||||
assert(!Number.isNaN(totalBytes), "Sanity check of content-length protocol");
|
assert(!Number.isNaN(totalBytes), "Sanity check of content-length protocol");
|
||||||
|
|
||||||
let readBytes = 0;
|
|
||||||
|
|
||||||
console.log("Downloading file of", totalBytes, "bytes size from", url, "to", destFilePath);
|
console.log("Downloading file of", totalBytes, "bytes size from", url, "to", destFilePath);
|
||||||
|
|
||||||
// Here reject() may be called 2 times. As per ECMAScript standard, 2-d call is ignored
|
let readBytes = 0;
|
||||||
// https://tc39.es/ecma262/#sec-promise-reject-functions
|
res.body.on("data", (chunk: Buffer) => {
|
||||||
|
readBytes += chunk.length;
|
||||||
|
onProgress(readBytes, totalBytes);
|
||||||
|
});
|
||||||
|
|
||||||
return new Promise<void>((resolve, reject) => res.body
|
const destFileStream = fs.createWriteStream(destFilePath, { mode: destFilePermissions });
|
||||||
.on("data", (chunk: Buffer) => {
|
|
||||||
readBytes += chunk.length;
|
await pipeline(res.body, destFileStream).catch(DownloadFileError.rethrow("Piping file error"));
|
||||||
onProgress(readBytes, totalBytes);
|
return new Promise<void>(resolve => {
|
||||||
})
|
destFileStream.on("close", resolve); // details on workaround: https://github.com/rust-analyzer/rust-analyzer/pull/3092#discussion_r378191131
|
||||||
.on("error", err => reject(
|
destFileStream.destroy();
|
||||||
new DownloadFileError(`Read-stream error, read bytes: ${readBytes}`, err)
|
});
|
||||||
))
|
|
||||||
.pipe(fs.createWriteStream(destFilePath, { mode: destFilePermissions }))
|
|
||||||
.on("error", err => reject(
|
|
||||||
new DownloadFileError(`Write-stream error, read bytes: ${readBytes}`, err)
|
|
||||||
))
|
|
||||||
.on("close", resolve)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user