如何使用node.js在浏览器中获取文件下载的状态

时间:2015-11-16 06:06:00

标签: node.js

在index.js中,我使用下面的代码下载文件并在控制台中显示该文件的状态。

但是,现在我尝试使用node.js在浏览器中显示该文件的状态。任何人都可以帮我解决这个问题...

我的index.js:

//Downloads the file and shows the status in the console
    var request = require('request');
    var progress = require('request-progress');
    var DOWNLOAD_DIR = '/usr/local/';
    var file_name = 'newgoogle.png' 

    var callback = function(state){
        console.log('received size in bytes', state.received);
        console.log('total size in bytes', state.total);
        console.log('percent', state.percent);

    } 

    progress(request('https://www.google.com/images/srpr/logo3w.png'), {
        throttle:0,   
        delay: 0       
    })
    .on('progress', callback) 

    .pipe(fs.createWriteStream(DOWNLOAD_DIR + file_name))
    .on('error', function (err) {
     console.log("error");  
    })
    .on('close', function (err){
    console.log("Download Complete"); 
    })

//Lists all the files and folders in the filesysytem 
app.get('/files', function(req, res) {


 var currentDir =  dir;
 var query = req.query.path || '';
 if (query) currentDir = path.join(dir, query);
 console.log("browsing ", currentDir);

 fs.readdir(currentDir, function (err, files) {
     if (err) {
        throw err;
      }
      var data = [];
      files
      .filter(function (file) {
          return true;
      }).forEach(function (file) {
        try {
                var stats = fs.statSync(path.join(currentDir,file));
                var time = stats["atime"];
                var date = time.toString().substr(4,11);

                var isDirectory = fs.statSync(path.join(currentDir,file)).isDirectory();
                if (isDirectory) {
                  data.push({ Name : file,Date : date, IsDirectory: true, Path : path.join(query, file)  });
                } else {
                  var ext = path.extname(file);
                  if(program.exclude && _.contains(program.exclude, ext)) {
                    console.log("excluding file ", file);
                    return;
                  }       
                  data.push({ Name : file,Date:date, Ext : ext, IsDirectory: false, Path : path.join(query, file) });
                }

        } catch(e) {
          console.log(e); 
        }        

      });
      data = _.sortBy(data, function(f) { return f.Name});
      res.json(data);
  });
});

在app.js中,我试图在数据表中显示数据。

我的app.js:

var currentPath = null;
   var options = {
        "bProcessing": true,
        "bServerSide": false,
        "bPaginate": false,
        "bAutoWidth": false,
         "sScrollY":"250px",
      "fnCreatedRow" :  function( nRow, aData, iDataIndex ) {
    if (!aData.IsDirectory) return;
    var path = aData.Path;
    $(nRow).bind("click", function(e){
        $.get('/files?path='+ path).then(function(data){
            table.fnClearTable();
            table.fnAddData(data);
            currentPath = path;
        });


        $.get('/directory?path='+ path).then(function(data){        
            $("input[name='location']").val(data.directory);
           //$("#showDiv").hide();
         });         
    e.preventDefault();
    });
},



        "aoColumns": [{"sTitle":"File Name", "mData": null, "bSortable": false, "sClass": "head0", "sWidth": "55px",
            "render": function (data, type, row, meta) {
              if (data.IsDirectory) {
                return "<a href='#' target='_blank'><i class='fa fa-folder'></i>&nbsp;"  + data.Name +"</a>";
              } else {
                return "<a href='/" + data.Path + "' target='_balnk'><i class='fa " + getFileIcon(data.Ext) + "'></i>&nbsp;" + data.Name +"</a>";
              }
            }
          },
            {"sTitle":"Date",align: 'Center', "mData": null, "bSortable": false, "sClass": "head1", "sWidth": "55px",
            "render": function (data, type, row, meta) {
              if (data.IsDirectory) {
                 return  data.Date;
             }else{
               return data.Date;

             } 
            }
          },
        {"sTitle":"Status",align: 'Center', "mData": null, "bSortable": false, "sClass": "head1", "sWidth": "55px",
            "render": function (data, type, row, meta) {
              if (data.IsDirectory) {
                 return "";
             }else{
               return "";

             }
            }
          }
        ]   

     };

  var table = $(".linksholder").dataTable(options);

  $.get('/files').then(function(data){
      table.fnClearTable();
      table.fnAddData(data);
  });

$.get('/directory').then(function(data){        
    $("input[name='location']").val(data.directory);
   $("#showDiv").hide();
});

我目前的格式:

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要在进度回调函数中使用Socket.IO,这是维护客户端与服务器之间一致通信的正确方法。