Monday 10 April 2017

NodeJS- How to sequentially create a file and then read from?

I'm entirely new to NodeJS and this problem has been bugging me for days now. I'm pulling my hairs to find a working solution. I'm trying to get information from the database and pass it to a text file where I later read from it. I cannot do it sequentially. It always reads it first and then creates it. I don't know what way I should take to overcome the issue. Any working solution/ways will help tremendously.

My connection file that retrieves information from the database:

this.getInfo = function() {
return new Promise(function(resolve, reject){
  db.query('SELECT ai_code from user_code',
    function(err,rows){
      if(err)
        reject(err);
      resolve(rows);
  });
 });
}

module.exports = 
{
    getInfo: this.getInfo
}

Functions that calls the method to receive data.

function team1Code(){
    db.getInfo().then(function(result){
       var code = JSON.stringify(result[0]);
       var c = json2plain(code, options);
       c = c.replace('Ai_code:','');
       fs.writeFile('./scr1.js', c, { overwrite: true, encoding: 'ascii' },function (err) {
        if (err) return console.log(err);
       });
    });
}
function team2Code(){
    db.getInfo().then(function(result){
        var code = JSON.stringify(result[1]);
        var c = json2plain(code, options);
        c = c.replace('Ai_code:','');
        fs.writeFile('./scr2.js', c, { overwrite: true, encoding: 'ascii' },function (err) {
            if (err) return console.log(err);
        });
    });
}

Finally, this is where we try to read the content of the files.

vmHandler.init = function(apiValues) {
    team1Code();
    team2Code();
  // Team 1
    try{
      vmHandler.team1.scriptCode = fs.readFileSync('./scr1.js');
      vmHandler.team1.script = new vm.Script(vmHandler.team1.scriptCode);
      vmHandler.team1.sandbox = { api: new Api(apiValues, 1) }
      vmHandler.team1.context = new vm.createContext(vmHandler.team1.sandbox);
    }catch(err){}
  // Team 2
    try {
      vmHandler.team2.scriptCode = fs.readFileSync('./scr2.js');
      vmHandler.team2.script = new vm.Script(vmHandler.team2.scriptCode);
      vmHandler.team2.sandbox = { api: new Api(apiValues, 2) }
      vmHandler.team2.context = new vm.createContext(vmHandler.team2.sandbox);
    } catch(err) {
      console.log("ERROR: " + err);
    }
};



via V G

No comments:

Post a Comment