我想确保在使用之前确实有一个文件要下载,fs.createWriteStream
因为现在它会下载一个 404 页面并将其保存为 xls 文件...
我已经编写了以下代码。我该如何实现它,如果失败,我希望能够向 slack 发送消息
async function downloadFile() {
function switchCase(value) {
switch (value) {
case '1':
return 'jan';
case '2':
return 'fev';
case '3':
return 'mar';
case '4':
return 'abr';
case '5':
return 'mai';
case '6':
return 'jun';
case '7':
return 'jul';
case '8':
return 'ago';
case '9':
return 'set';
case '10':
return 'out';
case '11':
return 'nov';
case '12':
return 'dez';
default:
return;
}
}
(async function (url, dest) {
return new Promise((resolve, reject) => {
var file = fs.createWriteStream(dest);
var request = https
.get(url, function (response) {
response.pipe(file);
file.on('finish', async function () {
resolve(true);
file.close();
await closeDB();
});
})
.on('error', async function (err) {
fs.unlink(dest);
reject(err);
await fetch(
`https://hooks.slack.com/services/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`,
{
method: 'post',
body: JSON.stringify({
text: `url: ${url}, dest: ${dest}, error: ${err}`,
}),
headers: { 'Content-Type': 'application/json' },
}
);
});
});
})(
`https://www.anbima.com.br/informacoes/merc-sec-debentures/arqs/d${
new Date().getFullYear().toString().slice(2) +
switchCase((new Date().getMonth() + 1).toString()) +
(new Date().getDate() - 1).toString().padStart(2, '0')
}.xls`,
'd' +
new Date().getFullYear().toString().slice(2) +
(new Date().getMonth() + 1).toString() +
(new Date().getDate() - 1).toString().padStart(2, '0') +
'.xls'
);
}