# @xhmikosr/downloader [![npm version](https://img.shields.io/npm/v/@xhmikosr/downloader?logo=npm&logoColor=fff)](https://www.npmjs.com/package/@xhmikosr/downloader) [![CI Status](https://img.shields.io/github/actions/workflow/status/XhmikosR/download/ci.yml?branch=master&label=CI&logo=github)](https://github.com/XhmikosR/download/actions/workflows/ci.yml?query=branch%3Amaster)

> Download and extract files

*See [download-cli](https://github.com/kevva/download-cli) for the command-line version.*

## Install

```sh
npm install @xhmikosr/downloader
```

## Usage

```js
import fs from 'node:fs';
import download from '@xhmikosr/downloader';

(async () => {
	await download('http://unicorn.com/foo.jpg', 'dist');

	fs.writeFileSync('dist/foo.jpg', await download('http://unicorn.com/foo.jpg'));

	download('http://unicorn.com/foo.jpg').pipe(fs.createWriteStream('dist/foo.jpg'));

	await Promise.all([
		'http://unicorn.com/foo.jpg',
		'http://cats.com/dancing.gif'
	].map(url => download(url, 'dist')));
})();
```

### Proxies

To work with proxies, read the [`got documentation`](https://github.com/sindresorhus/got/blob/main/documentation/tips.md#proxying).

### SSL

TLS certificate verification is enabled by default. It honors npm's [`strict-ssl`](https://docs.npmjs.com/cli/v11/using-npm/config#strict-ssl) config, so running `npm config set strict-ssl false` disables it for self-signed certificates or proxy setups. Override per call with [`options.got.https.rejectUnauthorized`](https://github.com/sindresorhus/got/blob/v14.6.6/documentation/5-https.md).

## API

### download(url, destination?, options?)

Returns both a `Promise<Buffer>` and a [Duplex stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex) with [additional events](https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md#events).

#### url

Type: `string`

URL to download.

#### destination

Type: `string`

Directory to save the file to.

#### options

##### options.got

Type: `Object`

Same options as [`got`](https://github.com/sindresorhus/got#options).

##### options.decompress

Same options as [`decompress`](https://github.com/XhmikosR/decompress#options).

##### options.extract

* Type: `boolean`
* Default: `false`

If set to `true`, try extracting the file using [`decompress`](https://github.com/XhmikosR/decompress).

##### options.filename

Type: `string`

Name of the saved file.

##### options.hash

Type: `string`

Expected hash of the downloaded data as `"<algorithm>:<hex>"`, checked before it's extracted or written. A mismatch throws. `algorithm` is any digest [`crypto.createHash`](https://nodejs.org/api/crypto.html#cryptocreatehashalgorithm-options) accepts.

```js
await download('http://unicorn.com/foo.tar.gz', 'dist', {
	hash: 'sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
});
```
