* This method is **deprecated**. * * Please use `handleDownloads()` instead.
(locator, customName)
| 1338 | * Please use `handleDownloads()` instead. |
| 1339 | */ |
| 1340 | async downloadFile(locator, customName) { |
| 1341 | let fileName |
| 1342 | await this.page.setRequestInterception(true) |
| 1343 | |
| 1344 | const xRequest = await new Promise(resolve => { |
| 1345 | this.page.on('request', request => { |
| 1346 | console.log('rq', request, customName) |
| 1347 | const grabbedFileName = request.url().split('/')[request.url().split('/').length - 1] |
| 1348 | const fileExtension = request.url().split('/')[request.url().split('/').length - 1].split('.')[1] |
| 1349 | console.log('nm', customName, fileExtension) |
| 1350 | if (customName && path.extname(customName) !== fileExtension) { |
| 1351 | console.log('bypassing a request') |
| 1352 | request.continue() |
| 1353 | return |
| 1354 | } |
| 1355 | customName ? (fileName = `${customName}.${fileExtension}`) : (fileName = grabbedFileName) |
| 1356 | request.abort() |
| 1357 | resolve(request) |
| 1358 | }) |
| 1359 | }) |
| 1360 | |
| 1361 | await this.click(locator) |
| 1362 | |
| 1363 | const options = { |
| 1364 | encoding: null, |
| 1365 | method: xRequest._method, |
| 1366 | uri: xRequest._url, |
| 1367 | body: xRequest._postData, |
| 1368 | headers: xRequest._headers, |
| 1369 | } |
| 1370 | |
| 1371 | const cookies = await this.page.cookies() |
| 1372 | options.headers.Cookie = cookies.map(ck => `${ck.name}=${ck.value}`).join(';') |
| 1373 | |
| 1374 | const response = await axios({ |
| 1375 | method: options.method, |
| 1376 | url: options.uri, |
| 1377 | headers: options.headers, |
| 1378 | responseType: 'arraybuffer', |
| 1379 | onDownloadProgress(e) { |
| 1380 | console.log('+', e) |
| 1381 | }, |
| 1382 | }) |
| 1383 | |
| 1384 | const outputFile = path.join(`${store.outputDir}/${fileName}`) |
| 1385 | |
| 1386 | try { |
| 1387 | await new Promise((resolve, reject) => { |
| 1388 | const wstream = fs.createWriteStream(outputFile) |
| 1389 | console.log(response) |
| 1390 | wstream.write(response.data) |
| 1391 | wstream.end() |
| 1392 | this.debug(`File is downloaded in ${outputFile}`) |
| 1393 | wstream.on('finish', () => { |
| 1394 | resolve(fileName) |
| 1395 | }) |
| 1396 | wstream.on('error', reject) |
| 1397 | }) |