While my co-worker has written a vast majority of the code, I finally found some free time to dive in, and one of the first things I began playing with was finding a way to stream the output of a unix process to the view. Of course the obvious choice was to use WebSockets and Socket.IO and I quickly found a couple examples that made it look like it wouldn’t be too hard.
In my evening-long codefest, I came across two interesting quirks with Socket.IO/node that took up a majority of my time, and I thought I’d detail them here in case anyone else runs into similar issues:
We’re currently using a WebWorker object to handle an out-of-request process, the output of which I want to stream to the view. Inside the worker I created some code that looked like the following (just as an initial test for using
This isn’t quite exactly what it was doing, but suffice it to say that the output I got wasn’t what I expected; it instead was this:
Needless to say, I was quite confused, until I logged the output on the server side and saw this:
A short google trip later and I found this in the node.js docs so I updated my code to call
data.toString('ascii') and was rewarded with the output I expected.
The next time-consuming bug came when trying to stream the output from the process to the view. The build worker that handles running the process passes the output back to the controller, which then broadcasts it via the socket to the clients. My initial code looked something along these lines:
However, I was unable to call
stderr off the object passed in the broadcast, and when I logged to the browser console I found this odd output:
At first glance I was confused, it looked like a JSON object or an object literal, but I had no access to any of the keys inside. I thought to myself “The secret must lie in the ‘~j~’ at the beginning,” but Google returned no relevant results regarding that. Eventually, after reading several other examples, I found a simple solution:
By doing this, I was able to access
stderr off the
data variable. I’m still uncertain what the object originally being passed to the view was, as it was neither JSON nor an object literal, but the solution got me where I needed to be. If anyone can explain it further, please do so; I’d love to know what’s going on behind the scenes here.