如何使用socket.io显示使用Node.js

时间:2015-11-16 12:29:14

标签: node.js socket.io

我可以使用Node.js下载文件并显示并获取进度。我想使用socket.io

显示浏览器的进度

任何人都可以帮助我......

我的代码:

var request = require('request');
var progress = require('request-progress');

var DOWNLOAD_DIR = '/usr/local/';
var file_name = 'googlenew.png' 


//displays progress on download on console
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"); 
})

enter image description here

1 个答案:

答案 0 :(得分:3)

因为您已经能够使用Node.js下载文件并获取服务器端的进度,所以您可以将此信息发送到客户端上的套接字。

//get connected
var chat = io.of("/socket").on('connection',onSocketConnected);

function onSocketConnected(socket){
   console.log("connected :"+socket.id);  
}

//in your existing callback function of progress
//send info to client 
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);
    io.sockets.emit('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: fileName}));

} 

然后,在客户端,您必须根据收到的信息使用HTML-CSS-JS更新您的进度条。您可能需要考虑this library进度条。下面的代码段使用建议的库。

<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap.css" />

<div id="progressbar">
</div>

<script>
  var socket = io('http://localhost');
  socket.on('connect', function(){});
  socket.on('message', function(data){
    $('#progressbar').progressbar({
    maximum: 100,
    step: JSON.parse(data).percent
    });
  });
  socket.on('disconnect', function(){});
</script>