在Node.js中,引用同一个文件中的另一个函数会导致“ReferenceError:-function- is not defined”错误

在node.js应用程序中,尝试从同一文件( index.js )中的另一个函数内引用一个函数会导致错误ReferenceError:familyLookup未定义

意图是有第二个function, 时间表 ,调用familyLookup 。 我怎样才能解决这个问题?

index.js

exports.familyLookup = function(oid, callback){ var collection = db.get('usercollection'); collection.findOne( { _id : oid }, { address: 1, phone: 1 }, function(e, doc){ console.log(doc); } ) } exports.schedule = function(db, callback){ return function(req, res) { var lookup = familyLookup(); var schedule_collection = db.get('schedule'); var today = new Date(); var y = []; schedule_collection.find({ date : {$gte: today}},{ sort: 'date' },function(err, docs){ for ( var x in docs ) { var record = docs[x]; var oid = record.usercollection_id; result = lookup(db,oid) record.push(lookup(oid)); y.push(record); } res.render('schedule', { 'schedule' : y, }); }); }; }; 

关键的消息是ReferenceError:没有定义familyLookup 。 在你的代码中,你只是通过exports.familyLookup定义了如何使用你的index.js 。 换句话说,可以通过以下方式在其他文件中使用familyLookup

 // in foo.js var index = require('index'); index.familyLookup(fooDB, function(){/* */}); 

您应该在同一个文件中定义函数familyLookup() ,然后定义如何使用index.js

 // define function so that it can be used within the same file var familyLookup = function(db, callback) {/*...*/} // this line only defines how to use it out of `index.js` exports.familyLookup = familyLookup;