nodejs 下载文件并保存到指定目录

//文件下载
var thumb = ['http://abc.com/a.png'];
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("文件夹已存在");
}
let i = 0
let timer = setInterval(() => {
  let url = thumb[i];
  i++;
  let fileName = url.split('/').pop();
  let stream = fs.createWriteStream(path.join(dirPath, fileName));
  request(url).pipe(stream).on("close", function (err) {
    console.log("第" + i + "个文件[" + fileName + "]下载完毕");
  });
  if(i>=thumb.length) clearInterval(timer)
}, 500 + Math.random() * 1000)

你可能感兴趣的:(nodejs 下载文件并保存到指定目录)