NodeJS and CoffeeScript (coffee executable) not behaving the same?
I have a simple test.coffee which compiles to test.js
The test.coffee
process.on 'uncaughtException', (er) ->
console.log 'Unhandled exception'
console.log 'Unhandled exception'
console.log 'Unhandled exception'
console.log 'Unhandled exception'
console.log 'Unhandled exception'
console.log 'Unhandled exception'
console.log 'Unhandled exception'
console.log 'Unhandled exception'
return
throw new Error("aAH")
And the produced test.js
(function() {
process.on('uncaughtException', function(er) {
console.log('Unhandled exception');
console.log('Unhandled exception');
console.log('Unhandled exception');
console.log('Unhandled exception');
console.log('Unhandled exception');
console.log('Unhandled exception');
console.log('Unhandled exception');
console.log('Unhandled exception');
});
throw new Error("aAH");
}).call(this);
From the command line or from vim via (!node % and !coffee %) etc.. the outputs are surprisingly different.
node test.js behaves correctly and output several Unhandled exception lines to the console and exits. Invoking via 'coffee test.coffee' falls back to default behavior of printing the stack trace and exiting. This sample is obviously not my full app, but doing a bigger app开发者_开发百科 I couldnt get the unhandled exception to work when starting my ExpressJS app via coffee boot.cofee, what am I doing wrong? This is latest Node 0.4.8 and latest Cofee 1.1.1 on Mac OS X 10.6.x
When you run CoffeeScript code through the coffee
command, the code is compiled to JS and then run programmatically within a Node process. In particular, CoffeeScript uses the command
mainModule._compile code, mainModule.filename
(see coffee-script.coffee), where mainModule
is a reference to require.main
. That's why in the stack trace, you should see
Error: aAH
at Object. (.:12:9)
at Object. (.:13:4)
at Module._compile (module.js:404:26)
...
One side-effect of this that you've hit on is that exceptions will never go all the way down to the process
level. Instead, it's getting caught from thanks to this code
try
...
else if o.run then CoffeeScript.run t.input, t.options
...
catch err
...
in command.coffee.
The CoffeeScript takes several steps to simulate a "pure" Node.js process when you run coffee foo.coffee
, but there will always be some differences between running CoffeeScript directly and running compiled JS. For complex apps like the one you're developing, I'd suggest setting up a Cakefile so that you can automatically recompile, test, and run your app on save, rather than using your editor's built-in run command.
精彩评论