pythonnode.jscron

start node.js script from python script in crontab


Ubuntu 22.04.2 LTS

Python3.11

Node v22.2.0

I'm trying to run a node.js script from a Python script by running a Python script from crontab, but nothing happens exactly in the part where the node.js script is running, the Python script is executed correctly

node.js script (1.js):

const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, '3.txt');
const currentDate = new Date().toLocaleString();

fs.appendFileSync(filePath, `${currentDate}\nTest\n`, 'utf8', (err) => {
    if (err) {
        console.error('error:', err);
        return;
    }
    console.log('all done');
});

python script:

#!/usr/bin/python3.11
import subprocess      
  
print("start script")
   
result = subprocess.run(['node', '1.js'], capture_output=True, text=True)

if result.returncode == 0:
    print("end script")
else:
    print("Script execution failed.")

I tried specifying the full path:

/usr/bin/node
subprocess.run(['/usr/bin/node', '1.js'], capture_output=True, text=True)

I tried connecting os and set os.environ:

import os
os.environ['PATH'] += ':/usr/bin/node'

Nothing helped, always "Script execution failed." - when it is launched from crontab, although when launched simply from the terminal from the user - everything works

all files are "775" and "+x"


Solution

  • result = subprocess.run(['/usr/bin/node', '/home/ubuntu/node_script/test/1.js'], check=True, capture_output=True, text=True)
    

    specifying the absolute path to the node.js script is mandatory even if both scripts are in the same directory