Cannot set breakpoint inside function when using require inside closure - node.js

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:~ $

I ran exactly into the same issue with the same setup.
I've added a breakpoint after the definition of the target-function (that was the only place i could actually add a breakpoint). When the debugger reached that breakpoint and the function was actually defined, i was able to add breakpoints to the actual target-function...

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:
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.
No need to wrap your code in an anonymous function when in Node.

Related

How do I find what files use a specific function or file in a Node project, using VSCode?

I'm working with a Node project using VSCode. I'd like to be able to follow the tree upwards from functions/files at a lower level. That is, if I have an exported function doSomething in file dosomething.js, I'd like to see what code calls this function, and/or see what code requires this file.
// index.js
const { doSomething } = require('./tricky-stuff')
// tricky-stuff.js
const doSomething = function() {}
module.exports = {doSomething}
If I'm browsing tricky-stuff.js, is there a built-in feature to VSCode that allows me to see usages of either the function doSomething or where the file tricky-stuff.js is required/imported, so that it would show me the file index.js in this case (as well as perhaps other files where tricky-stuff is used)? Is there any extension? I seem to recall that WebStorm could do this, but I can't remember. (I know I could search for strings, but that seems inelegant).
I think it largely depends on how much VScode knows about your code, via the TypeScript language service or JSDoc comments etc...
Typically you can right click on a function and select the peek all references or find all references options:
In this case, it will show you all the places where that function is called or referenced.

node js behaviour for this keyword

Let's have a look to this very basic program.js:
console.log(this);
Here is the output:
$ nodejs program.js
{}
Now, if i do the samething in the repl console:
$ nodejs
> console.log(this)
I see a log of things at undefined at the end.
Why do we not get the same result ?
Thanks
You are experiencing two different behaviors because you're basically executing code in two different environments.
In program.js, this answer applies. You're in a node.js module, so this is the same as module.exports.
In the node.js repl, this answer applies. You're not in a node.js module; you're in the repl which uses the global context. this is the same as global. If you executed the same code in-browser, it'd reference the window object instead of global.

Node Server debugger code behavior changes when debugging

I am debugging a Node Server written in typescript in WebStorm 10.0.4 and when stepping through the code, the code execution path completely changes. A variable assignment appears to break and reference a different (incorrect) object and break my code.
I have a class CustomerRoutes.ts which contains different methods to handle POST requests. I register the endpoint:
app.post('/Contacts', jsonParser, CustomerRoutes.postContact);
CustomerRoutes.postContact is a public static function which is defined as:
public static postContact(request, response) {
if(request.body.$type == 'Person') {
CustomerRoutes.postIndividual(request, response);
} else if(request.body.$type == 'Organization') {
CustomerRoutes.postOrganization(request, response);
}
}
CustomerRoutes.postIndividual and CustomerRoutes.postOrganization are both public static functions as well. So when the server is in non-debug mode the code executes as expected and the branching statements are executed. However when stepping through the code the variable CustomerRoutes global variable gets reassigned to the contents of request within the scope of CustomerRoutes.postContact
As you can see in the Variables window of the debugger the variable CustomerRoutes has been redefined twice to the values of request and response. So now when stepping through the code and the functions postIndividual and postOrganization are called, CustomerRoutes does not contain those function and POST fails with an exception and error 500.
I do not believe this is any sort of race/timing condition so it must be a bug in the debugger environment. My hunch is that the typescript variable mappings are not working correctly with the debugger but I am not certain. Has anyone seen an issue like this or an idea on a fix? I have never seen anything like it. I am happy to post more information as requested.
My hunch is that the typescript variable mappings are not working correctly with the debugger but I am not certain.
TypeScript doesn't have proper variable mapping in sourcemaps at the moment. Follow this issue : https://github.com/Microsoft/TypeScript/issues/2859 (also answered it here once : Chrome Typescript debugging references wrong 'this')
Has anyone seen an issue like this or an idea on a fix?
Disable sourcemaps to see what is actually going on in the raw JavaScript.

Nodejs and implicit global variables?

I'm using some external libraries intended to be used in a browser and they set global variables implicitly like a='a' (without the var).
It seems like when I require certain scripts that do this, sometimes the variable will be accessible outside its scope just like in a browser, but for other scripts the global variable is not accessible outside its own script.
Anyone know how nodejs handles implicit global variables, and why I'm seeing somewhat random behavior? I found surprisingly little on the internet.
I can go into the scripts. write something like
if(typeof exports !== 'undefined' && this.exports !== exports){
var GLOBAL=global;
}
else{
var GLOBAL=window;
}
and then change all implicit references to GLOBAL.reference but these scripts are not my own and every time I want to get the latest version of them I would have to do this over again, which is clearly not desirable.
Using module.exports would be cleaner because then I don't have change all the references, but just add a section of the top of every file that exports the globals, but my original question about how node handles implicit globals is still relevant
I am not sure if this answer will help you, since it is hard to diagnose what is going on with your code, but maybe, some of this reasonings can help you diagnose the actual problem in your code.
The behavior in node is actually similar to that of the browser. If you would declare a variable without the var keyword the variable will be accesible through the global object.
//module foo.js
a = 'Obi-wan';
//module bar.js
require('./foo');
console.log(global.a); //yields Obi-wan
console.log(a); //yields Obi-wan
It is not clear why you say this behavior is not consistent in your code, but if you think about it, the use of global variables is precisely subject to this kind of problems since they are global and everyone could overwrite them at any time, causing as a result this unexpected conditions.
There is one aspect in which node is different from the browser though and that could be affecting the behavior that you see.
In the browser, if you do something like this directly in a JavaScript file:
console.log(this==window); //yields true
But if you do the same thing in a Node.js module:
console.log(this==global); //yields false
Basically, in the outer scope of a Node.js module the this reference points to the current module.exports object.
console.log(this==exports); //yield true
So, chances are that if you are putting data in the global scope (window) in the browser through the use of this, you may end up with a module scope in Node.js instead.
Interestingly, the code inside a function in Node.js behaves pretty much as in the browser, in terms of the use of the global scope.
(function what(){
console.log(this==global); //yields true
})();
This does not directly answer your question but it provides a solution since I don't think it is possible.
I love regexp. They are so powerful:
js = js.replace(/^(\t|\s{4})?(var\s)?(\w+)\s=/gm, function () {
if (arguments[1] || arguments[2]) return (arguments[1] || '') + (arguments[2] || '') + arguments[3] + ' =';
return 'exports.' + arguments[3] + ' =';
});*
JSFiddle here
How does it work? I will retrace my work:
/(\w+)\s=/g will take any var, return 'exports.' + arguments[1] + ' ='; will turn them into an export. Not very good.
/(var\s)?(\w+)\s=/g will take any var, but in the callback we examined first group (var\s). Is it undefined? Then we should export it, else nothing should happen. But what about scopes?
/^(\t|\s{4})?(var\s)?(\w+)\s=/gm now we use indent to determine the scope :)
You should be able to run this regex on your file. Be careful, you need it properly indented, and be aware that I might have forgotten some things.
Ah, the problem was that the global variable that was being declared globally in the browser wasn't being declared via a='a', but with var a='a'. In a browser if the var keyword is used not inside a function it will still declare a global variable. It only declares a local variable if the var keyword is inside a function. Node.js doesn't behave this way, and all var declarations are considered local.
Its ashame node.js does this, it makes it less compatible with browser scripts, for no real reason. (other than allowing people not to have to wrap all their scripts in a function).

Require.js (almond.js) Timing Off

I'm trying to use Almond.js and the Require.js optimizer to make a standalone file that can be used without Require.js. I've been able to successfully compile the file, and all the code runs, but there's one problem: the code executes in the wrong order.
Let's say my main file (the one that's in the include= option passed to the optimizer) has the following:
console.log('outside');
require(['someFile'], function(someModule) {
console.log('inside');
window.foo = someModule.rightValue;
});
and then out in my HTML I have:
<script src="myCompiledFile.js"></script>
<script>
console.log('out in the HTML');
</script>
Since I'm using almond.js and a compiled file (and therefore there's no file loading going on) I would expect to get the output:
outside
inside
out in the HTML
However, it turns out there's still some asynchronicity going on, because what I actually see is:
outside
out in the HTML
inside
and if I try to check window.foo from the HTML it's not there.
So, my question is, how can I get the code to be more like a normal/synchronous JS file, which runs all its code first before passing things on to the next script block? I can't exactly tell my users "wrap all your code in a window.setTimeout".
By default Almond replicates the timing semantics of RequireJS' require call. Since require is asynchronous in RequireJS, it is also asynchronous in Almond. This can be readily observed in the source: Almond uses a setTimeout to schedule the execution of a module even though it could execute it right away. It makes sense because in the general case developers don't expect that the code they've crafted to work asynchronously will suddenly become synchronous just because they are using Almond. It does not matter in every project but in a project where the UI (for instance) should be refreshed in a certain order, changing the timing semantics could break the code.
Two options:
As the comment just before the setTimeout states, using require('id') works globally with Almond. This is because once your bundle is loaded, everything is guaranteed to have been loaded (since Almond does not load dynamically).
There's also a way to call require with extra arguments. If the fourth argument is true, the call is going to be synchronous:
require(['someFile'], function(someModule) {
console.log('inside');
window.foo = someModule.rightValue;
}, undefined, true);
This can be ascertained by reading the code of Almond. There's no documentation I could find on forceSync (that's the name of the parameter in question) but some bug reports mention it and I've not seen any comment there that it is meant to be a private functionality.

Resources