将变量传递给exports对象

时间:2016-09-05 08:38:55

标签: node.js

我有两个文件,如何将值传递给变量?

sample.js:

module.exports = {
   content: [
    {
        table: {
            body: [
                [
                    { text: address, alignment: 'center'}
                ]
        }
    }
}

app.js:

var sample = require('sample');

如何将地址传递给样本对象?

4 个答案:

答案 0 :(得分:1)

function getContent(adress) {
  return content: [
    {
      table: {
          body: [
              [
                { text: address, alignment: 'center'}
              ]
        }
    }
}

module.exports = getContent;

app.js:

var sample = require('./sample')(adress);

答案 1 :(得分:1)

您想导出一个返回对象的函数:

module.exports = function (address) {
    return {
        content: [
            {
                table: {
                    body: [
                        {
                            text: address,
                            alignment: 'center'
                        }
                    ]
                }
            }
        ]
    }
};

现在您可以填写值:

var sample = require("./sample");
console.log(sample("fooAddress"));

答案 2 :(得分:0)

试试这个:

module.exports = (address) => {
  return {
    content: [
      {
        table: {
          body: [
            {text: address, alignment: 'center'}
          ]
        }
      }
    ]
  }
}

var sample = require('sample')('The address');

答案 3 :(得分:0)

您可以将module.exports变为函数:

<强> sample.js

module.exports = (address) => { return { content: [
  {
    table: {
      body: [
        {text: address, alignment: 'center'}
      ]
    }
  }
] };}

<强> app.js

var sample = require('sample')('your address parameter');