I've been fumbling around with this issue for what has seemed like weeks, and I cannot get the issue resolved.
I spent days trying to get to where I can be able to call the actual function outside of the original .js file.
All I want to be able to do in node.js is create a function that will be able to generate a random number within a specific parameters such as (1-10 or 1-100), and relay it back to the console or a variable specified by the user.
This is the current code that I have:
server.js
var myModule = require("./my_module.js");
console.log("your random number is" + myModule.hello(10)); //<-- the 10 represents the TOP number that will generate, if you look in the proceeding file, it adds a 1 to it as required by the code
my_module.js
function hello(foo) {
return Math.floor((Math.random()*foo)+1);
}
module.exports.hello = hello;
The issue that underlines here is i get a NaN, ( not a number ) from the console. I realize that this means somewhere in translation, the number may be turning into a string and not being able to be read by the mathFloor string.
You can use the jQuery method isNumeric to validate whether they gave you a number. http://api.jquery.com/jQuery.isNumeric/
To make sure it is still a number and you didn't inadvertently make it a string, use parseInt() or parseFloat().
function hello(foo) {
return Math.floor((Math.random()*parseInt(foo))+1);
}
While Erik's answer solves the problem, it won't tell you where the string is coming from. You can use console.trace to make your debugging life easier.
function hello(foo) {
var result = Math.floor((Math.random()*parseInt(foo))+1);
if (isNaN(result)) {
console.trace("result is NaN")
}
return result;
}
> hello("a")
Trace: NaN
at hello (repl:4:9)
at repl:1:2
at REPLServer.self.eval (repl.js:109:21)
at Interface.<anonymous> (repl.js:248:12)
at Interface.EventEmitter.emit (events.js:96:17)
at Interface._onLine (readline.js:200:10)
at Interface._line (readline.js:518:8)
at Interface._ttyWrite (readline.js:736:14)
at ReadStream.onkeypress (readline.js:97:10)
at ReadStream.EventEmitter.emit (events.js:126:20)
at emitKey (readline.js:1058:12)
at ReadStream.onData (readline.js:807:7)
NaN
>
By looking at the stack trace you will be able to find the code that provided a non-Number parameter.