The file download of Node.js mainly solves one of my needs recently.
Requirement Description:
How to store the files uploaded by Tencent cloud in a local directory? If you use js to implement it, pure JavaScript does not have such a function (maybe there is). Just because I use node.js more in this project, I can use the rich API of node.js to implement this function.
The following example code demonstrates downloading a remote file:
The source code is as follows (download.js):
//Download parameters var http = require("http"); var fs = require("fs"); var path = require("path"); var downFlag = false; var downUrl = ''; var downFileName = ''; /** * Download callback */ function getHttpReqCallback (imgSrc, dirName, fileName) { var callback = function(res) { console.log("request: " + imgSrc + " return status: " + res.statusCode); var contentLength = parseInt(res.headers['content-length']); var downLength = 0; var out = fs.createWriteStream(dirName + "/" + fileName); res.on('data', function (chunk) { downLength += chunk.length; var progress = Math.floor(downLength*100 / contentLength); var str = "Download:"+ progress +"%"; console.log(str); //Writing file out.write(chunk, function () { //console.log(chunk.length); }); }); res.on('end', function() { downFlag = false; console.log("end downloading " + imgSrc); if (isNaN(contentLength)) { console.log(imgSrc + " content length error"); return; } if (downLength < contentLength) { console.log(imgSrc + " download error, try again"); return; } }); }; return callback; } /** * Download start */ function startDownloadTask (imgSrc, dirName,fileName) { console.log("start downloading " + imgSrc); var req = http.request(imgSrc, getHttpReqCallback(imgSrc, dirName, fileName)); req.on('error', function(e){ console.log("request " + imgSrc + " error, try again"); }); req.end(); } startDownloadTask('http://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-8/v8.5.41/bin/apache-tomcat-8.5.41.tar.gz','D://1024Workspace//extension','apache-tomcat-8.5.41.tar.gz'); //startDownloadTask('Download address','Local storage path','file name');
The code has been tested, no problem.
The main references are as follows:
Download Node.js file