node.js - 通过 crontab 执行 NodeJS 会抛出错误

标签 node.js linux npm cron

我有一个使用discord.js 模块的NodeJS 脚本。 当我通过终端执行它时,它完美地工作。

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');

但是,当我使用 crontab 安排它时

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

我收到此错误

/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)

最佳答案

Crontab 执行了一个过时的分发 Node 包,该包位于/usr/bin/

解决方案是使用普通用户安装的 Node 版本,位于/usr/local/bin

这就是 crontab 行的样子:

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

关于node.js - 通过 crontab 执行 NodeJS 会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63629311/

相关文章:

javascript - javascript/NodeJS 中的变量范围问题

google-chrome-extension - 是否可以在 chrome 扩展中需要 npm 模块?

linux - 如何安装 Node 和 NPM,这样我就不必使用 sudo?

npm - 为什么我在执行 npm install 时会看到这个

javascript - 为什么未定义被添加到我的过滤列表中?

javascript - 如何在 Sequelize 模型上实现 'replyingTo' 和 'replies' 关联

node.js - Sequelize 关联

python - 跨进程共享 psycopg2/libpq 连接

linux - awk group by 并在符合条件时打印

linux - Qt Creator 编译错误 "cannot find -lGL"。其他解决方案不起作用