diff --git a/packages/lib/src/file_ops.ts b/packages/lib/src/file_ops.ts index 16701808..7aa5d8df 100644 --- a/packages/lib/src/file_ops.ts +++ b/packages/lib/src/file_ops.ts @@ -2,7 +2,6 @@ * @module lib/file_ops */ import crypto from "crypto"; -import events from "events"; import fs from "node:fs/promises"; import path from "path"; import stream from "stream"; @@ -258,7 +257,8 @@ export async function createTempWriteStream(filePath: string) { async function discardPartialDownload(writeStream: stream.Writable, tempFilePath: string) { if (!writeStream.closed) { writeStream.destroy(); - await events.once(writeStream, "close"); + // Not events.once, it rejects if the stream is still erroring from the aborted pipe. + await new Promise(resolve => writeStream.once("close", resolve)); } try { await fs.unlink(tempFilePath); diff --git a/test/lib/file_ops.js b/test/lib/file_ops.js index a44e069f..efd29ced 100644 --- a/test/lib/file_ops.js +++ b/test/lib/file_ops.js @@ -412,6 +412,20 @@ describe("lib/file_ops", function() { await assert.rejects(fs.readFile(downloadPath), { code: "ENOENT" }); }); + it("should not leave a temporary file behind if interrupted while writing", async function () { + const downloadPath = path.join(downloadDir, "interrupted-writing.txt"); + onStream = (res) => { + res.write(Buffer.alloc(1024 * 1024)); + setTimeout(() => res.destroy(), 100); + }; + await assert.rejects(lib.downloadFile(new URL("/stream", baseUrl), downloadPath, "rename")); + await assert.rejects( + fs.readFile(path.join(downloadDir, "interrupted-writing.tmp.txt")), + { code: "ENOENT" }, + ); + await assert.rejects(fs.readFile(downloadPath), { code: "ENOENT" }); + }); + it("should throw if overwriteMode is rename and directory disappeared", async function () { if (process.platform === "win32") { // Can't remove the directory while the stream is running on Windows.