之前就已经写过一篇 浅谈 js 异步,最近有人问我怎么写批量下载。
方案有很多,用 request 模块自己封装一个 Promise 实现批量下载,用封装好的 got 模块直接批量,用递归批量。递归就不写了。
request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| const request = require("request"); const fs = require("fs"); const path = require("path");
const requestPromise = (url,filenane) =>{ return new Promise((resolve)=>{ request .get(url) .on("error", function(err) { console.error(err); }).on("end", () => { resolve(); }) .pipe(fs.createWriteStream(filenane)); }); }
async function loop(){ for (let index = 0; index < array.length; index++) { const url = array[index]; const file = path.basename(url); await requestPromise(url,file); } }
|
got
这个原本就支持 Promise
1 2 3 4 5 6 7 8 9 10 11 12
| const got = require('got'); const fs = require("fs"); const path = require("path");
async function loop(){ for (let index = 0; index < array.length; index++) { const url = array[index]; const file = path.basename(url); await got.stream(url).pipe(fs.createWriteStream(file)); } } loop();
|