人最宝贵的是生命。它给予我们只有一次。人的一生应当这样度过:当他回首往事时不因虚度年华而悔恨,也不因碌碌无为而羞耻。这样在他临死的时侯就能够说:"我已把我整个的生命和全部精力都献给最壮丽的事业—为人类的解放而斗争"。新浪微博

node.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('下载地址','本地存储路径','文件名');
  

 

posted @ 2018-05-22 10:02  草根玉堂  阅读(3206)  评论(0编辑  收藏  举报