module.export和全局对象

时间:2019-01-15 16:34:11

标签: javascript node.js node-modules node-https

我很困惑。

有时,当我的Web api接收到数据时,它会将数据混合在对象之间,并且在我看来,文件中的全局对象实际上是持久的。

这是代码的基本布局

handlers.js

const something = require('./otherfile')
let handlers ={}

handlers.customers = function (data, callback) {
  let acceptableMethods = ['post'];
  if (acceptableMethods.indexOf(data.method) > -1) {
    handlers._customers[data.method](data, callback);
  } else {  
    callback(405); 
  }
};

handlers._customers = {}

handlers._customers.post = async function (data, callback) {
  customer.new(data);
  callback(200, 'success')
}

otherfile.js

let contacts_list = [];
let accountData = {};

module.exports = something = {
  new: {
      dostuff: async function (data) {
      // update and reference global objects here..
      accountData.name = data.name;
      accountData.otherProperty = await somefunction(data.prop)
    }
  }
}

我希望,由于它需要一个导出模块,因此每次调用该导出模块时,都将其视为自己的对象,但是,似乎该对象并未被视为唯一对象,而是被覆盖了部分和“随机”。这对我来说意味着我可以导出一个变异对象,例如跨文件的数组

我是否正确,因为全局是在多个请求之间持久存在的? 在导出对象中设置全局变量会以任何方式影响该对象的行为吗?在这种情况下,我不希望这些数据发生变异。

在此先感谢您的建设性批评和指导:)

1 个答案:

答案 0 :(得分:1)

[重新组织代码,以便您在每个请求上创建一个新对象。模块是在第一个需求上缓存的,因此所有变量和对象属性将在调用之间保留。

// handler.js



const somethingFactory = require('./otherfile')

module.exports = function(){
  let handlers = {}
  const something = somethingFactory();

  handlers.customers = function (data, callback) {
    let acceptableMethods = ['post'];
    if (acceptableMethods.indexOf(data.method) > -1) {
      handlers._customers[data.method](data, callback);
    } else {  
      callback(405); 
    }
  };

  handlers._customers = {}

  handlers._customers.post = async function (data, callback) {
    customer.new(data);
    callback(200, 'success')
  }

  return handlers;

};

otherfile.js

module.exports = function(){
  let contacts_list = [];
  let accountData = {};

  return {
     new: {
      dostuff: async function (data) {
      // update and reference global objects here..
      accountData.name = data.name;
      accountData.otherProperty = await somefunction(data.prop)
     }
    }
  }

};

相关问题