javascripthtmlnode.jsbashshelljs

How to call a "JS file" by a html "button-click" and the JS file is running a bash script using shell.js


I want to connect to the "server.js" file by a html-button click.

The "server.js" file is running a "bash.sh" file using shell.js

Can anyone give some ideas or directions on how to proceed?

button.html

<!DOCTYPE html>
<html>
<body> 

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

<script src="server.js"></script>

</body>

client.js

function myFunction() {
      document.getElementById("demo").innerHTML = "Hello World";
    }

server.js

const shell = require('shelljs');
shell.exec('./bash.sh')

bash.sh

#!/bin/bash

printf "command 1 is running...\n\n"

mlpack_linear_regression --training_file aircon.csv -v -M lr.xml

printf "\ncommand 2 is running...\n\n"

mlpack_linear_regression --training_file aircon.csv --test_file 
predict.csv --output_predictions_file prediction.csv -v

printf "\nPredicted Output: \n\n"

cat prediction.csv # after this command the result should shown on 
                   #the browser screen


echo "hello" >> file # To test if connection is happening or not 
                     #by writing a string in a file

Solution

  • Look at the documentation for shell.js. It says:

    Portable Unix shell commands for Node.js

    You are trying to use it in a web browser. It is not designed to run in a web browser and will not work there.

    You need to run it using Node.js.


    You could write an HTTP server using Node.js, and then use Ajax (or just a regular link click or form submission) to make an HTTP request to that server to cause it to do whatever you want to so with the shell.