0

I am working on a small chat app backend in NodeJS.

I am trying to make a plugin system for it, Is there some way that I can end the script any time I want.

My code

pluginLoadder.js

/**
 * Starts to load plugins
 * @param {function} cb Runs after all plugins are loaded
 */
function startPlugins(cb) {
  fs.readdir(pluginPath, function(err, files) {
    if (err !== null) {
      console.error(err);
    } else {
      const pluginFileREGEXP = /.+\.js$/;
      files = files.filter(function(value) {
        return pluginFileREGEXP.test(value);
      });
      files.forEach(function(val) {
        try {
          const tempPlugin = require(pluginPath +'/'+ val );
          const func = {
            events: events,
            log: log,
          };
          tempPlugin.main(func);
          events.emit('test');
        } catch (e) {
          if (e instanceof TypeError) {
            log(`ERROR: ${val} is not a talker-backend plugin\n
            E: ${e}`, 'error');
          } else {
            log(e, 'error');
          }
        }
      });
      cb();
    }
  });
}

./plugins/spamer.js

//* This is a plugin thats in the directory ./plugins
/* I want to stop this script through pluginLoader.js
*/
function main(func) {
  const {events, log} = func;
  setInterval(function (){
    log('test', 'event');
  }, 1000)
}
module.exports = {
  main: main
};
TarithJ
  • 25
  • 8
  • 1
    Hi Tarith, and welcome to SO. Could you give an example of where and when to stop the script? It might help with the context. A simple `return;` wherever you want to exit the script might be enough. – Christer Oct 09 '20 at 08:12
  • 1
    Does this answer your question? [How to exit in Node.js](https://stackoverflow.com/questions/5266152/how-to-exit-in-node-js) – Romuald Oct 09 '20 at 08:22
  • @Romuald It wasn't what I was asking for. I updated the question to make it more clear. – TarithJ Oct 09 '20 at 08:39

1 Answers1

1

In most cases you could use process.exit which takes in an exit code as an integer parameter (Node.js interprets non-zero codes as failure, and an exit code of 0 as success).

Then if you want to specifically target a process (assuming you are running multiple ones) you could use process.kill which takes process pid as a parameter.

Finally you could use process.abort which immediately kills Node.js without any callback executed and with a possibility to generate a core file.

To sum up:

// You would mostly use
process.exit(exitCode); // where exitCode is an integer

// or
process.kill(processPid);

// or
process.abort();

Just call it anytime you need to exit your program in your code.

Romuald
  • 175
  • 10