須要循環去下載遠程文件,而後本身寫了一個demo,能夠直接運行,以下:多線程
//文件下載 var fs = require("fs"); var path = require("path"); var request = require("request"); //建立文件夾目錄 var dirPath = path.join(__dirname, "file"); if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath); console.log("文件夾建立成功"); } else { console.log("文件夾已存在"); } //循環多線程下載 for (let i = 0; i < 60; i++) { let fileName = "out" + intToString(i, 3) + ".ts"; let url = "https://xxx.sdhdbd1.com/cb9/sd/gc/g1/670BC531/SD/" + fileName; let stream = fs.createWriteStream(path.join(dirPath, fileName)); request(url).pipe(stream).on("close", function (err) { console.log("文件[" + fileName + "]下載完畢"); }); } //整數轉字符串,不足的位數用0補齊 function intToString(num, len) { let str = num.toString(); while (str.length < len) { str = "0" + str; } return str; }
原文參考了:https://blog.csdn.net/tiantangyouzui/article/details/52841406app
//文件下載 var fs = require("fs"); var path = require("path"); var request = require("request"); var co = require("co"); //建立文件夾目錄 var dirPath = path.join(__dirname, "file"); if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath); console.log("文件夾建立成功"); } else { console.log("文件夾已存在"); } function* downFile(url, fileName) { return new Promise(function (resolve, reject) { request(url, function (error, response, body) { if (!error && response.statusCode == 200) { let stream = fs.createWriteStream(path.join(dirPath, fileName)); request(url).pipe(stream).on("close", function (err) { resolve("下載成功"); }); } else { if (error) { reject(error); } else { reject(new Error("下載失敗,返回狀態碼不是200,狀態碼:" + response.statusCode)); } } }); }); } co(function* () { //循環多線程下載 for (let i = 50; i < 500; i++) { // let fileName = "out" + intToString(i, 3) + ".ts"; // let url = "https://xxx.sdhdbd1.com/cb9/sd/gc/g1/DBC3A6CE/SD/" + fileName; let fileName = "/media_b500000_" + i + ".ts"; let url = "http://sjvodcdn.cbg.cn:1935/app_1/_definst_/smil:getnew/sobeyget/vod/2018/04/19/9bdcd66a74954c84a50375c608c0e692/1524106287_7835.smil" + fileName; try { let m = Math.floor(i / 50).toString();//50個文件一個文件夾 let cDir = path.join(dirPath, m); if (!fs.existsSync(cDir)) { fs.mkdirSync(cDir); console.log("文件夾[" + cDir + "]建立成功"); } yield downFile(url, path.join(m, fileName)); console.log("下載成功" + fileName); } catch (err) { console.log(err); break; } } }); //整數轉字符串,不足的位數用0補齊 function intToString(num, len) { let str = num.toString(); while (str.length < len) { str = "0" + str; } return str; }