简体   繁体   English

在node.js中导出并要求范围

[英]Exports and require scope in node.js

fighting for 5 days with the problem. 与问题战斗了5天。 I have 3 files, needed to share one varible kvmIndex between them 我有3个文件,它们之间需要共享一个变量kvmIndex

getKvmIndex.js getKvmIndex.js

var kvmIndex=[],
exports.kvmIndex = kvmIndex;
exports.getSNMP = function (callback) {
   async.each(switchIps, function(switchIp, callback1) {
   goGo(switchIp, callback1);
   }, function(err) {
        callback();
    })
};

match.js match.js

var app1 = require("./app.js");
var kvmIndex;
exports.kvmIndex = kvmIndex;
...

exports.matchAll = function(callback) {
async.series([
    function(callback) {
        kvmIndex = app1.kvmIndex;
        decToHex(callback);
    },
    function(callback){
        matchSt('getPortToSt2', callback);
    },
    function(callback){
        console.log(kvmIndex);    //Here it defined! Works good.
        callback()
    }
])
callback();
}

app.js app.js

var kvmSNMP = require('./getKvmIndex')
, match = require('./match')
, async = require('async')
, kvmIndex = [];
...
async.series([
function(callback) {
    kvmSNMP.getSNMP(callback);
},
function(callback) {
    exports.kvmIndex = kvmSNMP.kvmIndex;
    callback();
},
function(callback) {
    match.matchAll(callback);
},
function (callback) {
    kvmIndex = match.kvmIndex;
    callback();
},
function (callback) {
    console.log(match.kvmIndex); //Doesnt work(
    callback();
}
])

What i'm doing: 我在做什么:

  • Define blank variable 定义空白变量
  • Export it 导出它
  • Doing stuff with it globally 在全球范围内做事
  • Accessing it in app.js 在app.js中访问它

In getKvmIndex.js it works fine, but in match.js no. getKvmIndex.js中它可以正常工作,但在match.js中则不能。 Can anybody help me? 有谁能够帮助我?

You need to define kvmIndex in one module (file) and one only. 您只需要在一个模块(文件)中定义kvmIndex It that module, add to it exports like you do. 将该模块添加到其中,然后像您一样将其exports The other modules (files) need to require the module defining kvmIndex , and use it by accessing myModule.kvmIndex . 其它模块(文件)需要require限定模块kvmIndex ,并通过访问使用它myModule.kvmIndex

Notes: 笔记:

1) It would be nicer to export getKvmIndex() from getKvmIndex.js , and not the variable kvmIndex directly. 1)最好从getKvmIndex.js导出getKvmIndex() ,而不是直接从变量kvmIndex

2) You may have a bug in match.js -- the callback is called immediately. 2)您在match.js可能有一个错误-回调立即被调用。 Did you maybe mean to pass callback and the 2nd argument to async.series() ? 您是否打算将callback和第二个参数传递给async.series()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM