Executing NodeJS via crontab throws an error

Viewed 464

I have a NodeJS script that uses discord.js module. It works flawlessly when I execute it via terminal.

const fs = require('fs');
const Discord = require('discord.js');
client = new Discord.Client(); client.on('ready', async() => {
        console.log('I am ready!');
        const dev = await client.users.fetch(2396720);
        const json = JSON.stringify(dev);
        fs.writeFile('/var/www/html/discord.json', json, function (err) {
        if (err) throw err;
        console.log('Saved!');
        process.exit(0);
        });
});
client.login('Mjky_Pn3Bk');

However, when I schedule it using crontab

* * * * * node /var/www/UserToJSON/index.js >> /tmp/results.log 2>&1

I'm receiving this error

/var/www/UserToJSON/node_modules/discord.js/src/client/Client.js:41
    } catch {
            ^

SyntaxError: Unexpected token {
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/var/www/UserToJSON/node_modules/discord.js/src/index.js:8:11)
1 Answers

Crontab executed an outdated distribution node package, which was placed in /usr/bin/

The solution is to use a node version installed by a normal user instead, located in /usr/local/bin

This is how the crontab line should look like:

* * * * * /usr/local/bin/node /var/www/UserToJSON/index.js
Related