Search code examples
javascriptnode.jscallbacksocket.iojquery-file-upload

Node.JS single socket, multiple events (uploads)


I'm developing an upload tracker (progress bar, etc).

So for my front-end I use jQuery File upload. Back-end upload is done using separate workers and there I use Redis pub/sub. So to connect front and back-ends I use Node.JS (socket.io).

jQuery file upload has a "done" callback function that denotes reaching our file to the server.

This works absolutely fine for a single file.

Problem arises when I try upload 2+ files simultaneously. "done" callback function is getting attached to socket listeners 2+ times (correct me if I'm wrong) and as an output I get something like this:

579 " - progress: " 8.333333333333334
580 " - progress: " 8.333333333333334 
579 " - progress: " 16.666666666666668 
580 " - progress: " 16.666666666666668 
579 " - progress: " 25 
580 " - progress: " 25
....
579 " -> upload is finished!" 
580 " -> upload is finished!"

That was an example of uploading 2 files. Which doesn't make any sense at all, because they can only be processed one after another.

So it should look like this:

579 " - progress: " 8.333333333333334
579 " - progress: " 16.666666666666668 
579 " - progress: " 25
....

579 " -> upload is finished!"
580 " - progress: " 8.333333333333334
580 " - progress: " 16.666666666666668
....
580 " -> upload is finished!"

Node.js server-side works totally fine. This is a log from it:

RECEIVED  progress  FROM  upload-579
RECEIVED  progress  FROM  upload-579
RECEIVED  progress  FROM  upload-579
RECEIVED  progress  FROM  upload-579
RECEIVED  progress  FROM  upload-579
RECEIVED  progress  FROM  upload-579
RECEIVED  progress  FROM  upload-579
RECEIVED  progress  FROM  upload-579
RECEIVED  progress  FROM  upload-579
RECEIVED  progress  FROM  upload-579
RECEIVED  progress  FROM  upload-579
RECEIVED  done  FROM  upload-579
RECEIVED  progress  FROM  upload-580
RECEIVED  progress  FROM  upload-580
RECEIVED  progress  FROM  upload-580
RECEIVED  progress  FROM  upload-580
RECEIVED  progress  FROM  upload-580
RECEIVED  progress  FROM  upload-580
RECEIVED  progress  FROM  upload-580
RECEIVED  progress  FROM  upload-580
RECEIVED  progress  FROM  upload-580
RECEIVED  progress  FROM  upload-580
RECEIVED  progress  FROM  upload-580
RECEIVED  done  FROM  upload-580

It received messages from Redis channel and emits appropriate messages to the client side. I think problem lies somewhere on the client side, but I cannot figure out how to modify the code there to get what I want. Can something be done to separate them from each other?

P.S


Solution

  • The socket event callback on the client-side will fire for any emit messages from Node.js. That's why you are seeing duplicate log messages. Either send additional data in the socket message, or attach unique events.