【问题标题】:How share a variable between two files in Node.js如何在 Node.js 中的两个文件之间共享一个变量
【发布时间】:2012-10-20 14:26:22
【问题描述】:

使用 Node.js,如果我将app.js 写为:

  var commons = {
    title: 'myTitle',
    description: 'MyDesc',
    menu: {
      home: {
        label: 'Home',
        url: '/',
      },
      contacts: {
        label: 'Contacts',
        url: '/contacts'
      }
    }
  }

  console.log(commons);

我有这个输出...

  {
    title: 'myTitle',
    description: 'MyDesc',
    menu: {
      home: {
        label : 'Home',
        url: '/'
      },
      contacts: {
        label: 'Contacts',
        url: '/contacts'
      }
    }
  }

...它工作正常。 但是,如果我要从另一个文件(在同一路径中)加载 app.js 中的变量...

commons.js:

exports.commons = {
    title: 'myTitle',
    description: 'MyDesc',
    menu: {
      home: {
        label: 'Home',
        url: '/',
      },
      contacts: {
        label: 'Contacts',
        url: '/contacts'
      }
    }
  }

app.js:

var commons = require('./commons');      
console.log(commons);

我作为输出:

commons: {
        {
        title: 'myTitle',
        description: 'MyDesc',
        menu: {
            home: [Object],
            contacts: [Object]
        }
    }
 }

为什么会这样?如何正确地跨两个文件传递变量?

【问题讨论】:

  • 如果您的意思是[Object],那就是console.log 在对象嵌套过多时防止向控制台发送垃圾邮件的能力。 commons.menu.home.label 应该可以正常工作。我不知道为什么它会显示commons: { { - 你确定它会一个接一个地显示{ {吗?

标签: javascript node.js share


【解决方案1】:

在模块中,exports 是一个对象,其中包含在其他地方需要模块时导出的所有内容。因此,通过设置exports.commons = { ...,您基本上是在设置exports 对象的commons 属性。这意味着您将实际对象嵌套在另一个对象中以进行导出。

在您的其他模块中,您使用commons = require('./commons') 导入整个exports 对象。因此,您设置的实际 commons 对象位于 commons.commons

如果你不想将数据嵌套在另一个对象中,你可以直接设置exports对象,使用module.exports

module.exports = {
    title: 'myTitle',
    description: 'MyDesc',
    ....
}

然后导入按您的预期工作。

正如 pimvdb 所说,输出中的 [Object] 只是 console.log 所做的,它不会在层次结构中走得太深。数据仍然存在,当您按照上述说明删除第一级时,您可能会看到内容正常。

【讨论】:

    【解决方案2】:

    这是console.log 的深度。向commons 对象再添加一层会得到相同的响应。

    var commons = {
    title: 'myTitle',
    description: 'MyDesc',
    menu: {
      home: {
        mine: {
          label: 'Home',
          url: '/',
        }
      },
      contacts: {
        label: 'Contacts',
        url: '/contacts'
      }
    }
    }
    console.log(commons);
    

    给出这个响应:

    { title: 'myTitle',
      description: 'MyDesc',
      menu:
       { home: { mine: [Object] },
         contacts: { label: 'Contacts', url: '/contacts' } } }
    

    看到这个:https://groups.google.com/forum/#!topic/nodejs-dev/NmQVT3R_4cI

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多