Skip to content

Commit

Permalink
feat(pipeToPath): return the downloaded file path (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
sigmaSd authored Jan 2, 2023
1 parent 4886569 commit bac23c1
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ You can have downloads show a progress bar by using the `.showProgress()` builde

```ts
const url = "https://dl.deno.land/release/v1.29.1/deno-x86_64-unknown-linux-gnu.zip";
await $.request(url)
const downloadPath = await $.request(url)
.showProgress()
.pipeToPath();
```
Expand Down
13 changes: 12 additions & 1 deletion src/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,25 @@ Deno.test("$.request", (t) => {

step("pipeToPath", async () => {
const testFilePath = Deno.makeTempFileSync();
const originDir = Deno.cwd();
try {
await new RequestBuilder()
const downloadedFilePath = await new RequestBuilder()
.url(new URL("/text-file", serverUrl))
.showProgress()
.pipeToPath(testFilePath);
assertEquals(Deno.readTextFileSync(testFilePath), "text".repeat(1000));
assertEquals(downloadedFilePath, testFilePath);
// test default path
Deno.chdir(Deno.makeTempDirSync()); // change path just to not download to the current dir
const downloadedFilePath2 = await new RequestBuilder()
.url(new URL("/text-file", serverUrl))
.showProgress()
.pipeToPath();
assertEquals(Deno.readTextFileSync("text-file"), "text".repeat(1000));
assertEquals(downloadedFilePath2, "text-file");
} finally {
try {
Deno.chdir(originDir);
Deno.removeSync(testFilePath);
} catch {
// do nothing
Expand Down
5 changes: 4 additions & 1 deletion src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,14 +294,17 @@ export class RequestBuilder implements PromiseLike<RequestResult> {
*
* @remarks If no path is provided then it will be derived from the
* request's url and downloaded to the current working directory.
*
* @returns The path of the downloaded file
*/
async pipeToPath(path?: string | URL, options?: Deno.WriteFileOptions) {
// Do not derive from the response url because that could cause the server
// to be able to overwrite whatever file it wants locally, which would be
// a security issue.
path = path ?? getFileNameFromUrlOrThrow(this.#state?.url);
const response = await this.fetch();
return await response.pipeToPath(path, options);
await response.pipeToPath(path, options);
return path;

function getFileNameFromUrlOrThrow(url: string | URL | undefined) {
const fileName = url == null ? undefined : getFileNameFromUrl(url);
Expand Down

0 comments on commit bac23c1

Please sign in to comment.