-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutility.ts
More file actions
38 lines (31 loc) · 942 Bytes
/
utility.ts
File metadata and controls
38 lines (31 loc) · 942 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { outputFile } from 'fs-extra';
import { join, parse } from 'path';
interface SaveOption {
type?: 'text';
sourceURL: string;
targetExtension?: string;
targetPath?: string;
}
export async function saveAs({
type = 'text',
sourceURL,
targetExtension = '',
targetPath = process.cwd()
}: SaveOption) {
const response = await fetch(sourceURL);
const { href, pathname } = new URL(response.url);
if (response.status > 299) {
const text = await response.text();
try {
var message = JSON.parse(text);
} catch {}
throw Object.assign(new URIError(response.statusText), {
cause: { sourceURL, message }
});
}
const data = await response[type]();
const path = join(targetPath, pathname),
{ ext } = parse(href);
await outputFile(ext ? path : path + targetExtension, data);
return { finalURL: href, data };
}