如何在Node.js中的两个文件之间共享变量

时间:2012-10-20 14:26:22

标签: javascript node.js share

使用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]
        }
    }
 }

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

2 个答案:

答案 0 :(得分:1)

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

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

如果您不想将数据嵌套在另一个对象中,只需使用exports直接设置module.exports对象:

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

然后导入按预期工作。

如pimvdb所说,输出中的[Object]只是console.log在层次结构中不会过深。数据仍然存在,如上所述,当你删除第一级时,你可能会看到内容很好。

答案 1 :(得分:0)

这是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

相关问题