简体   繁体   English

使用nodejs和socket.io将图像发送到客户端

[英]Sending images to the client with nodejs and socket.io

with the following code I'm able to send an Image to the client with socket.io, but I want also to send the size as a second argument. 使用以下代码,我可以使用socket.io将图像发送到客户端,但是我也想将大小作为第二个参数发送。 I would like to understand why the argument "size" is getting always undefined when I try to pass it to the socket.emit function. 我想了解为什么在尝试将参数“ size”传递给socket.emit函数时总是变得不确定。 socket.emit('firstChunkSent', data, size) . socket.emit('firstChunkSent', data, size) Can you pls fix it ? 你能解决这个问题吗?

var io = require('../server').io

io.sockets.on('connection', function (socket) {

socket.on('imageRequest', function () {  

getTheNewImage(function(data,size){

socket.emit('firstChunkSent', data, size)

  }); 
 }); 
});

function getTheNewImage(callback){

var filename = 'image.gif';

var base64FileSize  = fs.stat(filename,function(err,stats){

if (err) { throw err; }

return stats.size

});

var readable = fs.createReadStream(filename, { encoding: 'base64' });

readable.on('readable', function() {

var getImageData = function(){

  while (null !== (base64ImageData = readable.read())) {

          return base64ImageData
          }
}
callback(getImageData(),base64FileSize)

});

readable.on('end', function() {

console.log('there will be no more data.')

});

readable.on('error', function(err) {

console.log('here is the error: '+err)

readable.end(err);

});
return stats.size

Need to use the callback 需要使用回调

function getTheNewImage(callback){
    var filename = 'image.gif';
    var base64FileSize  = fs.stat(filename,function(err,stats){
    if (err) return callback(new Error(err));
    callback(null, stats.size)

});

getTheNewImage(function(data,size)

First param will be the error, not data 第一个参数将是错误,而不是数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM