简体   繁体   中英

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();

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

That's how it worked:

1- Moved notification-process.js file from assets folder to main directory.

2- Changed file path in main.js:

var child = new (forever.Monitor)(path.join(__dirname, 'notification-process.js')...

Without using join, it doesn't work after packaging the app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM