2013-01-23 46 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