2013-01-23 47 views
0

:)功能和module.exports错误问题NODE.js

我有一个简单的答案让你们回答,因为你总是这样做。 即时通讯新的功能和whatnot,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) 
+0

阅读本http://stackoverflow.com/questions/5311334/what-is-the-purpose-of-nodejs-module-exports-and如何使用它 – vinayr

回答

2

在randNum功能,不要忘了:

return randnumber; 

而且在index.js中,导出如下功能:

exports.randNumb = randNumb; 

调用它像这样在run.js:

console.log(randNumber(10)); 
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); 
+0

我有运行文件设置为 var index = require(“./ index.js”); console.log(index.randnumber); 我有索引文件 功能randNumb(topnumber){ 返回Math.floor(的Math.random()* topnumber) } module.exports.randnumber = randNumb(); 我刚刚从控制台 –

+0

'module.exports.randnumber = randNumb(10);' – OneOfOne