Dave Newton Dave Newton - 1 month ago 5
Javascript Question

Missing function name in NodeJS stacktrace; why?

NodeJS v0.10.31 under OS X, same behavior under NodeJS v0.12.2.

My stack trace doesn't show the

test
function name when called normally:

function test() {
throw new Error('Missing `test` in stack trace?');
}

try {
test();
} catch (e) {
console.trace(e);
}


Output:

Trace: [Error: Missing `test` in stack trace?]
at Object.<anonymous> (no_stack_in_node.js:8:11)
// etc.


If it's inside a
setTimeout
I see what I expect:

try {
setTimeout(test, 0);
} catch (e) {
console.trace(e);
}


Output:

Error: Missing `test` in stack trace?
at test [as _onTimeout] (no_stack_in_node.js:2:9)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)


In the browser I see the latter in both cases.

Is there something specific I'm missing, or is the environment of NodeJS's CLI interfering, e.g., the "top level object" behaves a bit differently?

Answer

In Node.js, all the code in a module will be wrapped in an anonymous function, like this

(function (exports, require, module, __filename, __dirname) {
    // our actual module code
});

So your actual code will be wrapped like this

(function (exports, require, module, __filename, __dirname) {
    function test() {
        throw new Error('Missing `test` in stack trace?');
    }

    try {
        test();
    } catch (e) {
        console.trace(e);
    }
});

See this answer for a detailed explanation.

So, when you are tracing the location of the e, it actually is in an anonymous function. That is why it says Object.<anonymous>

Comments