Update April 12th, 2012: Pull request adding error reporting to CoffeeScript with line mapping

Chances are that, if you code in CoffeeScript, you often find yourself facing a JavaScript exception telling you a problem occured on a specific line. Problem is that the line number in question in the one of the generated JavaScript, not your in CoffeeScript line number. Even worse, if you generate your JavaScript transparently, you wont have any JavaScript file to look into and the all process of finding where this error occored is even more frustrating.

Well, it seems like the future version of JavaScript could come to the rescue, but not before a few months. In the mean time, here’s a little of fun about writing a small Bash script that may save you some time.

We’ll call our script coffeep, an enhance version of coffee -p and it’s purpose is to print to the console the JavaScript code translated from your coffee file with line numbered. To make it even more useful, the script may take one or two additional arguments after the coffee file path to limit the printed lines to only the section which you wish to debug.

For example, coffeep myfile.coffee will output the generated JavaScript like coffee -p myfile.coffee would do, but with each line prefixed by its line number. Calling coffeep myfile.coffee 20 will print the line 20 as well as the 5 preceding lines and the 5 following lines. Calling coffeep myfile.coffee 20 30 will print the line 20 to 30.

This is certainly not rocket science but shall become part of your coffee swiss army knife. Leveraging cat -n which given some content passed through stdin prefix each line with its line number starting at 1, our first version of coffeep looks like:

If you are not familiar with bash scripting, $1 stands for the first argument passed to coffeep, which in our case is our coffee file.

Now we’ll add two possible usages. If one argument is provided after the path, it is expected to be the JavaScript line number you wish to debug and we’ll output the preceding and following 5 lines. If two arguments are provided after the path, there are expected to be the first line and the last line to output.

With some little arithmetic, we make use of head and tail to first limit the output to head_count first lines with head, and finally limit the output to tail_count last lines with tail.

Finally, for convenience, just copy/paste the following code into your terminal and it shall create an executable file named “coffeep” in “/usr/local/bin” (accessible from your $PATH, make sure to have the permission to modify this directory):