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.

4
  • 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: stackoverflow.com/questions/610839/… Commented Dec 15, 2022 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? Commented Dec 15, 2022 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. Commented Dec 15, 2022 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. Commented Dec 15, 2022 at 13:50

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.