0

:)

I have a somewhat easy answer for you guys to answer as you always do. Im new at functions and whatnot, iv watched some tutorials about exporting your functions to another node.js application,

Im attempting to generate some random numbers for a external module.

this is what i have setup.

(index.js file)


 function randNumb(topnumber) {
 var randnumber=Math.floor(Math.random()*topnumber)
 }

 module.exports.randNumb();

(run.js)


  var index = require("./run.js");


  console.log(randnumber);

Well My Issue is when i run the index.js file, i get this error from the console.

TypeError: Object #<Object> has no method 'randNumb'
    at Object.<anonymous> (C:\Users\Christopher Allen\Desktop\Node Dev Essential
     s - Random Number\index.js:8:16)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

I ran the run.js in the beginning, this is what i got.

    ReferenceError: randNumb is not defined
    at Object.<anonymous> (C:\Users\Christopher Allen\Desktop\Node Dev Essential
    s - Random Number\run.js:3:1)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)
Christopher Allen
  • 7,769
  • 5
  • 20
  • 35
  • read this http://stackoverflow.com/questions/5311334/what-is-the-purpose-of-nodejs-module-exports-and-how-do-you-use-it – vinayr Jan 23 '13 at 03:14

2 Answers2

2

In the randNum function, don't forget to:

return randnumber;

Also in index.js, export the function like so:

exports.randNumb = randNumb;

Invoke it like this in run.js:

console.log(randNumber(10));
Darren
  • 1,846
  • 15
  • 22
0

You didn't export the var at all.

Your index.js should be :

function randNumb(topnumber) {
   return Math.floor(Math.random()*topnumber)
}
module.exports.randnumber = randNumb(10); //replace 10 with any other number...

run.js should be :

var index = require("./run.js");
console.log(index.randnumber);
OneOfOne
  • 95,033
  • 20
  • 184
  • 185
  • I have the run file set as var index = require("./index.js"); console.log(index.randnumber); i have the index file as function randNumb(topnumber) { return Math.floor(Math.random()*topnumber) } module.exports.randnumber = randNumb(); I just get a NaN definition from the console – Christopher Allen Jan 23 '13 at 21:20
  • `module.exports.randnumber = randNumb(10);` – OneOfOne Jan 24 '13 at 01:36