0

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

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

4

2 回答 2

1

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

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

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

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

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

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

于 2012-10-20T14:35:43.363 回答
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

于 2012-10-20T14:33:50.587 回答