Having problem with starting a windows services using node-Windows

34 Views Asked by At

I'm trying to start a Windows service for fetching a data from an API in the background and update the local SQLite DB whenever there is an internet connection . Just to start with I had created a script which calls a Api and gets data from it and creates a text file . I'm trying to start the service by running the node file where I have linked the script File and all the other necessary details to Install and start the service. I'm able to install a service and see my service name in the Windows Services List .

Services

Even after running the service manually , The Script which is Linked is not running.

This is my code to install and start the script

BgSync.js

const Service = require('node-windows').Service;
const fs = require('fs');

const svc = new Service({
    name: 'MondialAutoSync',
    description: 'Auto Sync for DB',
    script: "D:\WindowService\SyncserviceApi.js" 
});


svc.on('install', function () {
    fs.writeFile('Test.txt', "TEsing", function (err) {
        if (err) throw err;
        console.log('Saved!');
      });
    try {
        svc.start();
    } catch (error) {
        fs.writeFile('Errors.txt', error.stack, function (err) {
            if (err) throw err;
            console.log('Error saved in Errors.txt');
        });
    }
});

svc.on('uninstall', function () {
    console.log('Uninstall complete.');
});

svc.on('error', function (error) {
    fs.writeFile('ServiceError.txt', error.stack, function (err) {
        if (err) throw err;
        console.log('Service error saved in ServiceError.txt');
    });
});


svc.install();
// svc.start();

This is my actual script


const axios = require('axios')
var fs = require('fs');
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('database.db');



fs.writeFile('Test.txt', "TEsing", function (err) {
  if (err) throw err;
  console.log('Saved!');
});

function insertData(result) {
  // Insert data into the SQLite UserMaster table
  const insertSql = `INSERT INTO electrondb (UserName, Password, FirstName, LastName, Email, Address1, Address2, UserCode, CountryId, CountyId, CityId, StateId, ZipId, Phone, RemoteAccessPassword, SecondPassword, UserGroupId, LastLogin, LastIPAddress, LastBrowser, CustomerId, BranchId, CreationDate, CreatedBy, ModifiedDate, ModifiedBy, Active, OwnerORSalesman, Loginid, PushPinPath1, PushPinPath2, PushPinPath3, PushPinPath4, PushPinPath5, DefaultWarehouseId, Initial, UserClassId, UpdatePwd, LastlogoutTime , UserId) VALUES (?, ?, ?, ?, ?,?,?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
  `;

  result.forEach((row) => {
    // console.log(row)
    db.run(
      insertSql,
      row.UserName,
      row.Password,
      row.FirstName,
      row.LastName,
      row.Email,
      row.Address1,
      row.Address2,
      row.UserCode,
      row.CountryId,
      row.CountyId,
      row.CityId,
      row.StateId,
      row.ZipId,
      row.Phone,
      row.RemoteAccessPassword,
      row.SecondPassword,
      row.UserGroupId,
      row.LastLogin,
      row.LastIPAddress,
      row.LastBrowser,
      row.CustomerId,
      row.BranchId,
      row.CreationDate,
      row.CreatedBy,
      row.ModifiedDate,
      row.ModifiedBy,
      row.Active,
      row.OwnerORSalesman,
      row.Loginid,
      row.PushPinPath1,
      row.PushPinPath2,
      row.PushPinPath3,
      row.PushPinPath4,
      row.PushPinPath5,
      row.DefaultWarehouseId,
      row.Initial,
      row.UserClassId,
      row.UpdatePwd,
      row.LastlogoutTime,
      row.UserId,
      
      (insertErr) => {
        if (insertErr) {
          console.error("Error inserting data:", insertErr);
        } else {
          console.log("Data inserted into UserMaster table");
        }
      }
    );
  });

}


function FetchAllData () {
  return new Promise((resolve, reject) => {
    try {
      const query = 'SELECT * FROM electrondb';  
      db.all(query, (err, rows) => {
        if (err) {
          console.error('Error executing SQL query:', err);
          reject(err);
        } else {
          console.log(rows);
          resolve(rows);
        }
      });
    } catch (err) {
      console.error('Error executing SQL:', err);
      reject(err);
    }
  });
}

  let head = {
    RequestKey: '***************0w==',
    "Content-Type": "application/json" ,
    // "Access-Control-Allow-Origin:": "http://localhost:3000"
}
  const requestOptions = {
    
    headers: head,
  };
  

  function compareArrays(array1, array2) {

    const mapArray1 = new Map();
  
    array1.forEach((obj) => {
      
      const key = obj.UserId; 
      mapArray1.set(key, obj);
    });
  
    
    const differentObjects = array2.filter((obj2) => {
      const key = obj2.UserId; 
      return !mapArray1.has(key);
    });
  // console.log( "Different", differentObjects)
    return differentObjects
  }
  

 
  
  

 

  return axios
    .get('https://****/****/mic*****1/g*****r', { headers: requestOptions.headers })
    .then(async(results) => {
        // console.log(results.data.Table)
        let LocalData = await FetchAllData()
      let DataFrmApi = results.data.Table
      if(LocalData && DataFrmApi) {
        const result = compareArrays(LocalData, DataFrmApi);
        console.log("Different",result)
        insertData(result)
      }
  

      


      // fs.writeFile('mynewfile3.txt', JSON.stringify(results.data.Table[0]), function (err) {
      //   if (err) throw err;
      //   console.log('Saved!');
      // });
 
      return results;
    })
    .catch((error) => {
      console.log("Error in Get Method " + error);
      fs.writeFile('Errors.txt', error, function (err) {
        if (err) throw err;
        console.log('Saved!');
      });
 
   
    });



This is my code .

0

There are 0 best solutions below