Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 29 additions & 30 deletions packages/cli-tools/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import * as os from 'os';
import * as path from 'path';
import * as fs from 'fs';
import * as stream from 'stream';
import {pipeline} from 'stream/promises';
import {randomUUID} from 'crypto';

import {CLIError} from './errors';
import logger from './logger';

async function unwrapFetchResult(response: Response) {
const data = await response.text();
Expand All @@ -20,36 +21,34 @@ async function unwrapFetchResult(response: Response) {
* Downloads the given `url` to the OS's temp folder and
* returns the path to it.
*/
const fetchToTemp = (url: string): Promise<string> => {
try {
return new Promise((resolve, reject) => {
const fileName = path.basename(url);
const tmpDir = path.join(os.tmpdir(), fileName);

global.fetch(url).then((result) => {
if (result.status >= 400) {
return reject(`Fetch request failed with status ${result.status}`);
}

if (result.body === null) {
return reject('Fetch request failed - empty body');
}

const dest = fs.createWriteStream(tmpDir);
const body = stream.Readable.fromWeb(result.body);

body.pipe(dest);

body.on('end', () => {
resolve(tmpDir);
});
const fetchToTemp = async (url: string): Promise<string> => {
const result = await global.fetch(url);
if (result.status >= 400) {
throw new CLIError(`Fetch request failed with status ${result.status}`);
}
if (result.body === null) {
throw new CLIError('Fetch request failed - empty body');
}

body.on('error', reject);
});
});
} catch (e) {
logger.error(e as any);
throw e;
const fileName = path.basename(new URL(url).pathname) || 'download';
const tmpFile = path.join(
os.tmpdir(),
`react-native-cli-${randomUUID()}-${fileName}`,
);
const body = stream.Readable.fromWeb(result.body);
const dest = fs.createWriteStream(tmpFile, {flags: 'wx'});
let created = false;
dest.once('open', () => {
created = true;
});
try {
await pipeline(body, dest);
return tmpFile;
} catch (error) {
if (created) {
await fs.promises.unlink(tmpFile).catch(() => {});
}
throw error;
}
};

Expand Down
Loading