GauravP GauravP - 1 month ago 10
Javascript Question

Javascript code is not working in node?

I wrote a code to solve

this
keyword issues in
setTimeout()
function. And tried to run it in node and it showed throw err; can't find module error. Then I tried to run it in a browser and it worked. I mean how to know when to test our code in nodejs and when not. Or how can I improve my code. This is my code

function person () {
var firstName ;
var _this_ = this;

return {
saveContext: function(context) {
_this_ = context;
},
setName: function(name) {
_this_.firstName = name;
},
getName: function() {
console.log(_this_.firstName);
}
};
}

var employee1 = new person();
employee1.saveContext(employee1);

employee1.setName('Steve');
employee1.getName();

setTimeout(employee1.getName, 1000);

Answer

The "can't find module" error is thrown when:

  • You try running node on a non-existent file.

  • The file exists, but it's not in that directory.

  • You require a file which doesn't exist.