nodejs下载远程文件

nodejs下载远程文件

{{ detail.nickname }}

{{ formatTime(detail.create_time) }} 字数 {{ detail.content && detail.content.length }} 阅读 {{ detail.read_num }}

"```\nconst request = require('request');\nconst fs = require('fs');\nconst path = require('path');\n\nrouter.get('/download', function(req, res, next) {\n  // 创建目录\n  let dirPath = path.join(__dirname, \"../uploads/temp\");\n  if (!fs.existsSync(dirPath)) {\n    fs.mkdirSync(dirPath);\n    console.log(\"目录创建成功\");\n  } else {\n    console.log(\"目录已存在\");\n  }\n\n  // 下载远程文件到服务器\n  let url = 'https://mp32.9ku.com/upload/128/2020/04/17/1003659.mp3';\n  let filePath = path.join(dirPath, \"1003659.mp3\");\n  let fStream = fs.createWriteStream(filePath);\n  request(url).pipe(fStream).on(\"close\", function (err) {\n    console.log(\"文件[\" + \"1003659.mp3\" + \"]下载完毕\");\n\n    // 下载服务器文件到浏览器\n    res.download(filePath, (err) => {\n      if(err) {\n        res.send(err);\n      } else {\n        // 删除服务器临时文件\n        fs.unlinkSync(filePath);\n      }\n    });\n  });\n});\n````"
PS:写作不易,如要转裁,请标明转载出处。

如果此篇对您有帮助,可小额赞助,以兹鼓励!