Node.js之文件下載


Node.js之文件下載,主要最近解決我的一個需求。

需求描述:
如何將騰訊雲上傳的文件存儲到本地某個目錄下,如果用js來實現,純JavaScript沒有這樣的功能(也許有),正好我這個項目用node.js比較多,正好可以利用node.js豐富的API實現該功能。

如下示例代碼,演示下載遠程文件:

源碼如下(download.js):

//下載參數
var http = require("http");
var fs = require("fs");
var path = require("path");
var downFlag = false;
var downUrl = '';
var downFileName = '';

/**
 * 下載回調
 */
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 = "下載:"+ progress +"%";
            console.log(str);
            
            //寫文件
            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;
}

/**
 * 下載開始
 */
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('下載地址','本地存儲路徑','文件名');

代碼經過測試,沒有問題。

本文主要參考資料如下:
Node.js文件下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM