36 lines
1.3 KiB
TypeScript
36 lines
1.3 KiB
TypeScript
import * as childProcess from 'child_process';
|
|
|
|
/**
|
|
* Downloads a file using a curl child process, to allow for speed-limiting and timeout if download is too slow.
|
|
* Takes as input the host domain name, the path and the file size
|
|
*/
|
|
export default function downloadWithCurl({ host, path, tempFileName }: {host: string, path: string, tempFileName: string}): Promise<string> {
|
|
return new Promise(function(resolve, reject) {
|
|
const url = `http://${host}${(path.substr(0, 1) === '/' ? '' : '/')}${path}`;
|
|
|
|
const parameters: string[] = [
|
|
//...
|
|
'--silent',
|
|
'--limit-rate', '20m', //maximum speed of 20 MB/s = 160 MBit/s
|
|
'--speed-limit', String(Math.round(100 * 1024 * 1024 / 15)), //abort if less than 100 MB in 15 seconds
|
|
'--speed-time', '15',
|
|
'--output', tempFileName,
|
|
url,
|
|
];
|
|
|
|
const spawnedProcess = childProcess.spawn('curl', parameters);
|
|
|
|
spawnedProcess.stderr.setEncoding('utf8');
|
|
spawnedProcess.stderr.on('data', function(error) {
|
|
reject(`Error in process:\n> curl ${parameters.join(' ')}\n${error}`);
|
|
});
|
|
|
|
spawnedProcess.on('exit', function(code) {
|
|
if (code === 0) {
|
|
resolve(tempFileName);
|
|
} else {
|
|
reject(`Error in process:\n> curl ${parameters.join(' ')}\nNon-zero exit code ${code}.`);
|
|
}
|
|
});
|
|
});
|
|
}
|