Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use forever-monitor with Electron-Angular project?

I am using Angular 2 with Electron and want to keep running a process in background to show notifications. I am using forever-monitor for that, it works only in development mode, but when I package my app using electron-packager, this stops working. My code looks like that:

main.ts

exports.runBackgroundProcess = () =>  {

// Run a background process forever
var forever = require('forever-monitor');
var child = new(forever.Monitor)('src/assets/notification-process.js', 
{
  env: {ELECTRON_RUN_AS_NODE: 1},
  options: []
});

child.start();
}

I wrote a function in main.ts that will run background process when called from angular component. Code in notification-process.js is following:

notification-process.js

notifier = require('node-notifier')

notifierFun = (msg) =>  {
 notifier.notify({
 title: 'Notify Me',
 message: msg,
 wait: true
 });
}

var CronJob = require('cron').CronJob;

new CronJob('* * * * * *', function() {
  notifierFun("Message from notification process");
});

Finally I am calling the function from app.component.ts

let main_js  = this.electronService.remote.require("./main.js");
main_js.runBackgroundProcess();
like image 702
Nargis Avatar asked Apr 05 '19 13:04

Nargis


1 Answers

I don't think it is a good idea to set your script in the assets directory. I would prefer it to be packaged as an extra resource.

the next snippet will permit to launch your node process

  var child_process = require('child_process');
   var child = child_process.fork('notification-process.js',[],{
      cwd : 'resources'  
      }); 

If it does not work once packaged, this may be involved because your files have not been packaged .To package it as an extra resource, modify package.json as follow : this will package webserver folder to resources/webserver folder:

 "target": [
    "win": {
      "target": "nsis",
      "icon": "build/icon.ico",
       "extraResources" : [{
        "from" : "webserver",
        "to" : "webserver"}
    ]
    },

for reference, have a look at : https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options

like image 175
sancelot Avatar answered Oct 12 '22 00:10

sancelot