Search code examples
javascripthtmlnode.jsraspberry-pi2

Nodejs is not fully functional when running on autostart


I am currently trying to change the volume of my Raspberry Pi with two html buttons (volume up and volume down), using nodeJS. The volume change is done by calling a bash script when clicking on one of the html-buttons in index.html.

When I start node manually from terminal with

node server.js

everything works fine and I can increase and decrease the volume using the two buttons. As soon as I put the node script to autostart, only the "volume up" button is working, while the volume down does not seem to be working.

Killing the autostarted node process and starting it manually, it works just fine again. How can the outcome be this different, depending on how node is started here? What is my error in this?

My node script looks like this:

var express = require('express');
var path = require('path');
var open = require('open');
var fs = require('fs');
const { exec } = require('child_process');
var bodyParser = require('body-parser');

var port = 3000;
var app = express();

app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'index.html'));
});

app.use(bodyParser.urlencoded({ extended: false }));

app.post('/', function(request, respond) {
    var inputValue = request.body.volume;

    if (inputValue == "up") {
    exec('sh volumeup.sh');
}
    if(inputValue == "down") {
    exec('sh volumedown.sh');
}
});

app.listen(port, function(err){
    if(err){
        console.log(err);
    }else{
        open('http://localhost:' + port);
    }
});

with my index.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"/>
</head>
<body>
  <h2>Change Volume</h2>
  <form action="" method="post">
    <button name="volume" value="up">Volume Up</button>
    <button name="volume" value="down">Volume Down</button>
</form>
</body>
</html>

To get the nodejs to run on autostart, I have set up a *.desktop-file:

[Desktop Entry]
Encoding=UTF-8
Type=Application
Name=<Node>
Comment=
Exec=/usr/bin/node /home/pi/Desktop/server.js
StartupNotify=false
Terminal=true
Hidden=false

Thank you very much in advance, I really appreciate your help!


Solution

  • Figured it out by myself. In case anyone is facing a similar issue:

    What helped me, was to put both shell file names into their absolute path:

    ´´´

    app.post('/', function(request, respond) {
        var inputValue = request.body.volume;
    
        if (inputValue == "up") {
        exec('sh /home/pi/server/volumeup.sh');
    }
        if(inputValue == "down") {
        exec('sh /home/pi/server/volumedown.sh');
    }
    }); 
    

    ´´´

    Bothered me for longer than I want to admit :-)