0

I am currently developing an Electron app and need it to look into the crontab file and parse it.

How can Node.js (or something else in Electron) access the main crontab file and read it?

I looked into the cron-parser library but it is only able to read cron-formatted strings, not access the file.

Thanks in advance.

Diocrasis
  • 1
  • 1
  • Does it have to be the crontab file? If all you are trying to do is add cron jobs programmatically, just drop a file in /etc/cron.d/ with the cron format: https://stackoverflow.com/questions/610839/how-can-i-programmatically-create-a-new-cron-job – Guilherme Lofrano Corneto Dec 15 '22 at 13:00
  • @GuilhermeLofranoCorneto I can create another cron file if needed, but what I need is to read a cron file anyway. Is it more feasible to read and parse a custom cron file than to do it with the crontab one? – Diocrasis Dec 15 '22 at 13:06
  • The key thing here is that the crontab file isn't supposed to be read directly. If you run crontab -e repeatedly, you'll see a new tmp file will be generated each time. This temp file is just a mirror of whatever is under the current user in /var/spool/cron/crontabs, which also isn't supposed to be accessed directly. I'll write up an alternative as an answer. – Guilherme Lofrano Corneto Dec 15 '22 at 13:43
  • Just use the `fs` module and read what ever file you want... Keep in mind that your programm need the rights to read it. – Marc Dec 15 '22 at 13:50

1 Answers1

0

Since the crontab file we see when we run is just a tmp file that shows whatever cron jobs the current user has created (which are stored in /var/spool/cron/crontabs) when whe don't normally have access to those files, I'd suggest you run a shell script to get these data:

const { exec } = require("child_process");

exec("crontab -l", (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    //Do stuff with the read string on stdout
});

Hopefully this should give you the contents of the crontab under the user that's running the node script