Gridzbi Spudvetch
Gridzbi Spudvetch

Reputation: 39

Easy ways to quit and restart an entire script?

I have a Discord bot that I'm writing a restart function for. I want to be able to run one command that will not only stop the script, but kill and restart it, so I can implement updates quickly. I've realized that the Discord API is not sufficient for this so I haven't added it to the tags. The simplest way I can think of is by using two scripts that call each other.

Every resource I've found references either a module (?) called PM2 or a programming language called VBScript. I do not want to mess around with a module that automatically reboots every single time I save, and I especially don't want to try learning a new language.

Here is my pseudocode showing what I'm aiming for:

[bot.js]
function reboot() {
    runFile(`./reboot.js`)
}

[reboot.js]
kill (`./bot.js`)
runFile(`./bot.js`)

The result I'm hoping for is for bot.js to run reboot.js. Reboot.js will then quit bot.js and run it again. Then reboot.js will close. I don't care about any processes already running on bot.js.

Of course, if there are even simpler ways to do this, please let me know. I need as much simplicity as I can get.

Upvotes: 0

Views: 1186

Answers (3)

Gridzbi Spudvetch
Gridzbi Spudvetch

Reputation: 39

I've figured it out. I used the child-process module built into node.js.

[bot.js]

var cp = require('child_process');
function reboot() {
    var ls = cp.spawn('node', ['reboot.js']);
    client.destroy()
}


[full contents of reboot.js]

var cp = require('child_process');
var ls = cp.spawn('node', ['bot.js']);

(posting all this for fellow noobs to use)

Edit: Note that after restarting, console outputs no longer work, as it's running from reboot.js rather than directly from the terminal.

Upvotes: 1

Jed Richards
Jed Richards

Reputation: 12435

I'm not familiar with Discord bots, but if you want to start, kill and restart processes programmatically in NodeJS then you want to look into the child_process module.

https://nodejs.org/api/child_process.html#child_process_child_process

Upvotes: 0

Tim VN
Tim VN

Reputation: 1193

PM2 is a process manager and would do the trick for you.

It's easily installed: npm install pm2 -g

Start your bot: pm2 start bot.js --name "Discord Bot"

Code-wise, you'll want to simply kill the process. PM2, being a process manager, will restart it for you.

Upvotes: 1

Related Questions