函数和module.exports错误问题NODE.js

时间:2013-01-23 00:57:18

标签: node.js function random

:)

我有一个简单的答案让你们像往常一样回答。 我是函数和诸如此类的新手,iv观看了一些关于将函数导出到另一个node.js应用程序的教程,

我试图为外部模块生成一些随机数。

这就是我的设置。

(index.js文件)


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

 module.exports.randNumb();

(run.js)


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


  console.log(randnumber);

我的问题是当我运行index.js文件时,我从控制台收到此错误。

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)

我在开始时运行了run.js,这就是我得到的。

    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)

2 个答案:

答案 0 :(得分:2)

在randNum函数中,不要忘记:

return randnumber;

同样在index.js中,导出函数如下:

exports.randNumb = randNumb;

在run.js中调用它:

console.log(randNumber(10));

答案 1 :(得分:0)

你根本没有导出var。

你的index.js应该是:

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

run.js应该是:

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