我想从下面的'./models/devices-client.js'导出变量'result_array'
var config = require('./config');
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(config.dbadmin_uri, function (err, db) {
if (err) throw err;
// console.log('Successfully connected');
var collection = db.collection('repvpn2');
collection.find().toArray(function (err, result_array) {
// console.log('Found results:', result_array);
module.exports.Hosts = result_array;
db.close();
});
});
但是当在另一个文件中导入时,它打印'undefined'?
var Hosts = require('./models/devices-client').Hosts;
console.log(Hosts);
答案 0 :(得分:0)
让你的模块进行异步函数回调。
// JavaScript source code
var config = require('./config');
var MongoClient = require('mongodb').MongoClient;
module.exports = function (callback) {
MongoClient.connect(config.dbadmin_uri, function (err, db) {
if (err) throw err;
// console.log('Successfully connected');
var collection = db.collection('repvpn2');
collection.find().toArray(function (err, result_array) {
// console.log('Found results:', result_array);
callback(err, result_array);
db.close();
});
});
}
require('./models/devices-client')(function callback(err,Hosts) {
//Hosts Here
});