Sharing & modifying a variable between multiple files node.js

后端 未结 7 1154
日久生厌
日久生厌 2020-12-04 14:25

main.js

var count = 1;

// psuedocode
// if (words typed begins with @add)
require(\'./add.js\');

// if (words typed begins with @remove)
require(\'./remo         


        
7条回答
  •  孤城傲影
    2020-12-04 14:57

    I have same problem like you,.. Sometimes I'd like to sharing variables between multiple files because I love modular style eg. separating controller, function, models in different folders/files on my node.js script so I can easy manage the code.

    I don't know if this is the best solution but I hope will suit your needs.

    models/data.js

    // exports empty array
    module.exports = [];
    

    controllers/somecontroller.js

    var myVar = require('../models/data');
    myVar.push({name: 'Alex', age: 20});
    console.log(myVar);
    //  [{ name: 'Alex', age: 20 }]
    

    controllers/anotherController.js

    var myVar = require('../models/data');
    
    console.log(myVar);
    // This array has value set from somecontroller.js before...
    //  [{ name: 'Alex', age: 20 }]
    
    // Put new value to array
    myVar.push({name: 'John', age: 17});
    console.log(myVar);
    // Value will be added to an array
    //  [{ name: 'Alex', age: 20 }, { name: 'John', age: 17}]
    

提交回复
热议问题