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

なぜこうなった?2つのファイル間で変数を正しく渡すにはどうすればよいですか?

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行く深さです。オブジェクトにもう1つのレベルを追加する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 に答える