1
對不起,如果這是一個基本問題。我已經找到了關於創建模塊的信息,但是在使用模塊時沒有發現很多關於變量作用域的信息在nodejs中使用模塊的變量作用域
當我最初寫了我的程序,它被寫成一個單一的文件
var mongodb = require('mongodb');
var server = new mongodb.Server("192.168.199.10", 27017, {});
new mongodb.Db('syslog', server, {}).open(function (error, client) {
if (error) throw error;
var collection = new mongodb.Collection(client, 'messages');
collection.distinct("JUNOS.SRC.IP", function(err, results) {
var sessionCounts = [];
function parseSessionCounts(hosts, callback) {
var loop = 1,
numLoop = hosts.length;
hosts.forEach(function(element){
collection.find({"JUNOS.SRC.IP": element, "JUNOS.ACTION":'closed'}).count(function(err,count){
if (loop++ < numLoop){
sessionCounts.push({host:element,count:count});
} else {
sessionCounts.push({host:element,count:count});
callback();
}
})
});
}
parseSessionCounts(results, function() {
console.log(sessionCounts);
client.close();
});
})
});
爲了讓我的代碼重用,我爆發了parseSessionCount功能到一個模塊:
sessionCount.js
var sessionjs = require('./session'),
mongodb = require('mongodb'),
server = new mongodb.Server("192.168.199.10", 27017, {});
new mongodb.Db('syslog', server, {}).open(function (error, client) {
if (error) throw error;
var collection = new mongodb.Collection(client, 'messages');
collection.distinct("JUNOS.SRC.IP", function(err, results) {
var sessionCounts = [];
sessionjs.parseSessionCounts(results, collection, sessionCounts, function() {
console.log(sessionCounts);
client.close();
});
})
});
和session.js
module.exports = {
parseSessionCounts: function (hosts, collection, sessionCounts, callback) {
var loop = 1,
numLoop = hosts.length;
hosts.forEach(function(element){
collection.find({"JUNOS.SRC.IP": element, "JUNOS.ACTION":'closed'}).count(function(err,count){
if (loop++ < numLoop){
sessionCounts.push({host:element,count:count});
} else {
sessionCounts.push({host:element,count:count});
callback();
}
})
});
}
}
在進行此更改時,我注意到現在必須將變量(collection和sessionCounts)傳遞給函數,即使函數調用仍在變量定義的範圍內。是否還有另一種方法可以在不必傳遞變量的情況下執行此操作,或者這將始終是必需的,因爲它是一個定義在定義變量範圍之外的模塊?