Сбой загрузки; не отрабатывает участок кода
'use strict';
const NpmApi = require('npm-api');
const https = require('https');
const fs = require('fs');
const uuid = require('uuid');
async function getPackageList(){
const fname = uuid.v4();
const PACKAGE_LIST_PATH = `/tmp/npm-choice-${fname}.txt`;
const options = {
'host' : 'replicate.npmjs.com',
'keepAlive': true,
'path' : '/_all_docs',
'method' : 'GET'
};
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
if(res.statusCode != 200) reject(res.statusText);
let counter = 0;
let headers = JSON.stringify(res.headers, ' ', 2);
console.debug(`statusCode: ${res.statusCode}`);
console.debug(`headers: ${headers}`);
console.debug(`store data at ${PACKAGE_LIST_PATH}`);
res.on('data', (data) => {
fs.appendFile(PACKAGE_LIST_PATH, data, (err) => {
if (err) console.log(`at getPackageList: ${err}`)
else{
counter++;
process.stdout.write(`\rLoading ${counter} notes`);
}
});
});
}).end();
req.on('error', (error) => { reject(error); });
req.on('end', () => { resolve('######All done!'); });
});
}
async function main(){
let res = await getPackageList();
console.debug(`\n\n${res}`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
Результат:
statusCode: 200
headers: {
"date": "Wed, 27 Oct 2021 05:17:35 GMT",
"content-type": "application/json",
"transfer-encoding": "chunked",
"connection": "close",
"cache-control": "must-revalidate",
"x-couch-request-id": "undefined",
"x-couchdb-body-time": "0",
"strict-transport-security": "max-age=2592000000; includeSubDomains; preload;",
"vary": "Accept-Encoding",
"cf-cache-status": "DYNAMIC",
"expect-ct": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"",
"server": "cloudflare",
"cf-ray": "6a497574af604991-DME"
}
store data at /tmp/npm-choice-7eebfb96-0a72-4bad-b819-adebedc8bee6.txt
Loading 4808 notes
Проблемы:
- загрузка не завершается:
Loading 4808 notesвисит неограниченное количество времени при том, что ошибок сетевого подключения не выводится. Случается не всегда. Количество загруженных записей до повисания каждый раз варьируется. Как восстановить загрузку в таком случае? - участки кода
req.on('end', () => { resolve('######All done!'); });иconsole.debug(`\n\n${res}`);не отрабатывают даже в тех редких случаях, когда загрузка доходит до конца. Что я делаю не так?
Буду рад любой помощи, поскольку решений в сети найти не смог. Видимо у всех нормальных людей сеть мегастабильная и восстановление подключения не требуется.
Ответы (1 шт):
Автор решения: Alexey Ten
→ Ссылка
req это ClientRequest, у него нет события end.
Вам нужно слушать событие end у ответа res.
res.on('end', () => { resolve('######All done!'); });