Reputation: 21
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
};
Upvotes: 0
Views: 77
Reputation: 225
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.
Upvotes: 1