[带有javascript的nodejs axios和async等待模式的数组文件下载器

问题描述 投票:0回答:1

我在使用普通JavaScript编写脚本并在nodejs中运行时遇到问题。我想得到的是:

// Get axios request
  // response stream
  // download file1..........finish
// When file is downloaded 
// go to the next request 

// Get axios request
  // response stream
  // download file2..........finish
// When file is downloaded 
// go to the next request 

我在节点中编写此脚本并异步等待模式

// ARRAY OF BOOKS 
ex. [{title: 'awesome book', link: 'http://www.example.com/awesome_book.pdf'},
     {title: 'new book', link: 'http://www.example.com/new.pdf'} ...etc]
const Books = require('./Books');

const fs = require('fs');
const path = require('path');
const axios = require('axios');


// 1)
// loop the array of books and create array of links
let booksLinkinkArray = Books.map( book => book.link);

// 2)
// Function get request with axios
// response is stream
function request (element) {
  try{
    return axios({
      url: element,
      method: "GET",
      responseType: "stream"
    });
  } catch(e) {
    console.log( 'errore: ' + e)
  }
}


// 3)
// Function that downloads the file
async function download(urls) {
  urls.map(async url => {
    try{
      const saveFile = await request(url);
      let file = url.split('/')[3];
        console.log(file + ' :  ' + 'init download');
      let download = fs.createWriteStream(path.join(__dirname, 'books_dir', file));
      saveFile.data.pipe(download);
      console.log(file + ' :  ' + 'downloaded')

    } catch(e) {
      console.log( 'error: ' + e)
    }

  }) }

download(booksLinkinkArray);

此脚本可以,但是请求循环太快,文件下载重叠为:

// get request
// response
//download file init
// get request
// response
//download file init
ect...

file 1.......
file 2........
file 1...........
file 2..........
file 2.............. finish
file 1.............. finish

是否有一种方法来管理流,以便仅在从流中清除所有块之后才进行调用?

感谢您的答复

javascript node.js async-await stream axios
1个回答
0
投票
async download(){
  for(const url of urls) {
    .....
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.