console4Worker is console API for WebWorkers. WebWorkers are hard to debug. On top of that, console API is unavailable in WebWorkers. It doesn’t help.
console4Worker is a simple library which tries to fill this gap. It provides the console API , the same api you are used to. It implemented in most browser, node.js, even part of commonjs. See the demo in the examples/ directory.
On the Worker Side
First you include the script with this line.
1
|
|
And you are done! Now you can console API as you would normally do, even if you are in a webworker. Lets say something like
1
|
|
On the Page Side
On the page side, you need to add 3 lines. First to include the script, simply do
1
|
|
Then you bind console4Worker to your worker with another line.
1 2 3 4 |
|
If you got your own message event listener, add console4Worker.filterEvent()
in it.
This line will filter out messages coming from console4Worker.
So you should have something like
1 2 3 4 5 6 |
|
Motivation
Another project of mine is pacmaze. It uses webworkers to provide smoother animations. This is important for high fps game. The worst which can happen is to have 50fps most of the time but with short period at 30fps. People want the animation to be smooth.
Webworker allows to spread the load on 2 cpu core. Thus the pick of grabage collection is distributed, and you got twice more cpu power. So all in all, i found myself spending quite some time debugging webworker, so i wrote console4Worker to spend less time next time :)
Conclusion
How does it work ? a console object is declared in the worker. It intercepts all console calls and pass them to the page thread. a direct approach. I plan to add stacktrace and thus provide more accurate informations about the location of the call.
The code is available on github under MIT license. If you hit bugs, fill issues on github. Feel free to fork, modify and have fun with it :)