Pepezv131
Pepezv131

Reputation: 11

How can I do it synchronously in node js

I am new to Node.js and I want the code below run synchronously.
I want to move the DB to another place but I need to wait until the previous code finishes.

var exec = require('child_process').exec;
var sql = require('./connectDB');
var regedit = require('regedit');
var fs = require('fs');
var fse = require('fs-extra');

coll = "AT"

if (coll === "AT") {
  coll = "Latin1_General_CI_AS"
} else if (coll === "BG") {
  coll = "Cyrillic_General_CI_AS"
} else if (coll === "CZ") {
  coll = "Czech_CI_AS"
} else if (coll === "HU") {
  coll = "Hungarian_CI_AS"
}

console.log("Change of collation");

exec(
  `"c:/Program Files (x86)/Microsoft SQL Server/120/Setup Bootstrap/SQLServer2014/setup" /QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=hruza /SAPWD=ES_uni2004 /SQLCOLLATION="${coll}"`,
  function (err, stdout,stderr) {
    if (err) {
      console.error(`Setting of SQL collation error: ${err}`);
      console.log(`${stdout}`);
    }

    exec(
      `net start MSSQLSERVER`,
      function (err, stdout, stderr) {
      }
    )
    
    exec(
      `net start SQLBrowser`,
      function (err, stdout, stderr) {
      }
    )
    
    exec(
      `net start SQLWriter`,
      function (err, stdout, stderr) {
      }
    )

    sql.connectDB(
      `master`,
      `ALTER DATABASE master MODIFY FILE (NAME = master, FILENAME = 'c:/DB/DATABASE/Data/master.mdf')`,
      `ALTER DATABASE master MODIFY FILE (NAME = mastlog, FILENAME = 'c:/DB/DATABASE/Data/mastlog.ldf')`,
      function (err, out) {
        if (err) {
          console.error(`Setting of SQL collation error: ${err}`);
          console.log("Master DB location changed");
        }

        console.log("Writing registry SQL");

        var registryKey = 'HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQLServer\\Parameters';
        const registryValue = {[registryKey]: {
          'SQLArg0': {
            value: `-d$c:\\DB\\Database\\Data\\master.mdf`,
            type: 'REG_SZ'
          },
          'SQLArg1': {
            value: '-eC:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\Log\\ERRORLOG',
            type: 'REG_SZ'
          },
          'SQLArg2': {
            value: `-l$c:\\DB\\Database\\Data\\mastlog.ldf`,
            type: 'REG_SZ'
          }
        }
      };

      regedit.putValue(registryValue, function(err, result) {
        if (err) console.log(err)
          
        console.log(result);
      });

      console.log("Stop service SQL");

      exec(
        `net stop MSSQLSERVER`,
        function (err, stdout, stderr) {
        }
      )

      // moving db to another place but I need to wait to previous code finishs
      fse.move(
        'c:/Program Files (x86)/Microsoft SQL Server/MSSQL12.MSSQLSERVER/MSSQL/DATA/master.mdf',
        'c:/DB/Data/master.mdf',
        { overwrite: true }
      )

      fse.move(
        'c:/Program Files (x86)/Microsoft SQL Server/MSSQL12.MSSQLSERVER/MSSQL/DATA/mastlog.ldf',
        'c:/DB/Database/Data/mastlog.ldf', 
        { overwrite: true }
      )
  });
});

Upvotes: 0

Views: 279

Answers (2)

Subham Rajput
Subham Rajput

Reputation: 22

Callback function won't wait for the completion of code inside that. The easiest way to synchronous the code is to move the below file inside the callback function of sql.connectDB.

fse.move('c:/Program Files (x86)/Microsoft SQL Server/MSSQL12.MSSQLSERVER/MSSQL/DATA/master.mdf', 'c:/DB/Data/master.mdf', { overwrite: true })


fse.move('c:/Program Files (x86)/Microsoft SQL Server/MSSQL12.MSSQLSERVER/MSSQL/DATA/mastlog.ldf', 'c:/DB/Database/Data/mastlog.ldf', { overwrite: true })

Upvotes: 0

Geet Choubey
Geet Choubey

Reputation: 1077

The easiest trick is to see if the libraries have a promise() method and if you get lucky, sometimes they do.

However, in an unlikely event that they don't you can always wrap the callback functions (function(...) { ... }) inside a promise like this.

let promiseResult = await new Promise(function(resolve, reject) {
    sql.connectDB(`master`,`ALTER DATABASE master MODIFY FILE (NAME = master, FILENAME = 'c:/DB/DATABASE/Data/master.mdf')`,`ALTER DATABASE master MODIFY FILE (NAME = mastlog, FILENAME = 'c:/DB/DATABASE/Data/mastlog.ldf')`, function (err,out) {
    if (err) return reject(err);
    return resolve(out);
})

You will also have to wrap this code inside another async function

async function yourFunName() {
    let promiseResult = await new Promise(function(resolve, reject) {
        sql.connectDB(`master`,`ALTER DATABASE master MODIFY FILE (NAME = master, FILENAME = 'c:/DB/DATABASE/Data/master.mdf')`,`ALTER DATABASE master MODIFY FILE (NAME = mastlog, FILENAME = 'c:/DB/DATABASE/Data/mastlog.ldf')`, function (err,out) {
        if (err) return reject(err);
        return resolve(out);
    })
}

yourFunName().then(data => {
    console.log(data);
}).catch(err => {
    console.error(err);
})

Upvotes: 1

Related Questions