OpenAsar/src/updater/request.js

41 lines
1.1 KiB
JavaScript
Raw Normal View History

2022-01-19 18:16:35 +00:00
const request = require('request');
2021-12-09 16:25:14 +00:00
const nodeRequest = (opts) => new Promise((resolve, reject) => {
const { stream, timeout } = opts;
const req = request({ ...opts, timeout: timeout ?? 30000 });
2021-12-09 16:25:14 +00:00
2022-01-19 18:16:35 +00:00
req.on('response', (response) => {
const total = parseInt(response.headers['content-length'] || 1, 10);
let outOf = 0;
2022-01-19 18:16:35 +00:00
const chunks = [];
const badStatus = response.statusCode >= 300;
if (badStatus) stream = null;
response.on('data', chunk => {
chunks.push(chunk);
if (!stream) return;
outOf += chunk.length;
stream.write(chunk);
stream.emit('progress', [ outOf, total ]);
2021-12-09 16:25:14 +00:00
});
2022-01-19 18:16:35 +00:00
response.on('end', () => {
if (stream != null) {
stream.on('finish', () => resolve(response));
return stream.end();
}
if (badStatus) return reject(new Error('Req fail'));
2022-01-19 18:16:35 +00:00
resolve({ ...response, body: Buffer.concat(chunks) });
2021-12-09 16:25:14 +00:00
});
});
2022-01-19 18:16:35 +00:00
req.on('error', err => reject(err));
});
const meth = (method, opt) => nodeRequest({ ...(typeof opt === 'string' ? { url: opt } : opt), method });
exports.get = meth.bind(null, 'GET');