Search code examples
node.jsdebuggingrequirejswebstormnode-inspector

Cannot set breakpoint inside function when using require inside closure


Using node-inspector, I'm unable to set breakpoint in the following node.js code. (Content of main.js)

(function() {
    require('underscore');

    var doSomething = function(callback) {
        callback('doSomething Finished');
    }

    doSomething(function(x) {
       console.log(x);
    });

}).call(this);

I can easily set a breakpoint on line 2, line 4 or line 8, however no matter how hard I try the debugger won't let me set a break point on line 5 or line 9. To be clear, I'm using the following commands to run node-inspector

node --debug-brk main.js
node-inspector

I also tried to debug in web storm, however the issue persists. If I remove the line require('underscore');, then the problem immediately goes away and I'm able to set break point inside function body again. The problem also goes away if I remove the outermost closure function. It seems that the interaction between require and file level closure is screwing up the node debugging functionality. Has anyone experienced this problem themselves and / or knows any workarounds to be able to break inside function body?

EDIT: My node js version

Tony:~ $ node --version
v0.10.12
Tony:~ $ 

Solution

  • This may not be the answer that you want to hear as it doesn't explain why you can't set any breakpoints, but I would simply remove your require statement from the closure and place it top-level. I would go even further and recommend that you don't use a closure like the one above at all.

    The reason is that node uses its own module system, and unlike Javascript in the browser, declaring variables top-level does not pollute the global namespace. This is where require(...) comes in. So, you gain nothing by wrapping your code in an immediately invoked function (unless of course you want your module to be able to run both client side and server side).

    I would guess that the reason that you are not able to set any breakpoints is that the V8 runtime is recognizing an unnecessary closure and then optimizing your code for you. The rewritten code may not have the correct source mapping and so breakpoints cannot be set.

    So, two suggestions:

    1. require calls are not like regular statements. They are more similar to import statements in Java and are handled specially by the compiler. They should always be top-level in a node file.
    2. No need to wrap your code in an anonymous function when in Node.