我想通过cron运行我的脚本。但是,当我尝试执行它时,脚本无法启动。我在做什么错了?
sudo crontab -e:
5 * * * * /home/admin/.nvm/versions/node/v10.16.0/bin/node /home/admin/project/index.js
index.js:
#!/usr/bin/env node
...
var fs = require('fs');
function formatDate(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return day + '_' + monthNames[monthIndex] + '_' + year;
}
function formatTime(time) {
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
return hours + '_' + minutes + '_' + seconds;
}
var ws = fs.createWriteStream(`./log/test-${formatDate(new Date())}-${formatTime(new Date())}.log`, {
'flags': 'w',
'encoding': 'utf8'
});
process.stdout.wr = process.stdout.write;
process.stdout.er = process.stderr.write;
process.stdout.write = function (mes, c) {
ws.write(mes + '\r\n');
process.stdout.wr(mes, c);
};
process.stderr.write = function (mes, c) {
ws.write(mes + '\r\n');
process.stdout.er(mes, c);
};
...
grep CRON / var / log / syslog:
Jun 17 09:05:01 admin-serv CRON[861]: (admin) CMD (/home/admin/.nvm/versions/node/v10.16.0/bin/node /home/admin/project/index.js)
ps aux | grep index.js
admin 921 0.0 0.0 21320 1016 pts/0 S+ 09:05 0:00 grep --color=auto index.js
自然,当我运行此命令时
/home/admin/.nvm/versions/node/v10.16.0/bin/node /home/admin/project/index.js
通过终端,一切正常。
答案 0 :(得分:0)
process.stdout不起作用。如果您打算在没有终端的情况下运行脚本,则应该改用console.log。