0

I am a really recent starter with JavaScript. I have a simple Python Code, that opens a Bookmark for me and I want to create a Button in a .html that can run the code and open the bookmark.

This is my code so far:

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/3/w3.css">

<body>
<!-- Content will go here -->
<form>
    
    <script type="text/javascript">
        function randomSet() {

            const { spawn } = require("child_process");

            const childPython = spawn("python3", ["C:\\Users\\Rafi\\OneDrive\\Python\\random_set.py"]);

            childPython.stdout.on("data", (data) => {
                console.log(`stdout: ${data}`) ;
            });

            childPython.stderr.on("data", (data) => {
                console.error(`stderr: ${data}`) ;
            });

            childPython.on("close", (code) => {
                console.error(`child process exited with code ${code}`) ;
            });
        };
    </script>

    <label for="tip">Random Set!</label><br>
    <input id="choose_set" type="button" value="Listen Now!" onclick='randomSet()'><br>

</form>

</body>
</html>

If I run the function randomSet in a seperate .js file it works fine. Just the integration to HTML does not work. Why is that?

Rafii1
  • 29
  • 5
  • 1
    `require` is not a directive supported by any major browser. It is largely Node.js-specific. As such, you can’t use it in a browser context directly. – esqew Aug 16 '21 at 21:05
  • 1
    Don't know much about the specifics here, but I don't think you can do this in a browser. Browsers restrict access from JS to the os and file system so this sort of thing is usually not allowed (instead you must use special APIs to access the file system). As esqew's linked question suggests, you are trying to use Node-specific functionality in a browser, which doesn't always work (and in this case will not). You either need to rework your code to run in the browser in JS or create a server that your client can interact with (the server can use this Node code just fine). – Henry Woody Aug 16 '21 at 21:08
  • Thank you for your answers, I now understand why its not working. Would you be so kind to link me some lead links to follow up on creating a server for this specific purpose? In the end I just want to run this code locally on my Computer – Rafii1 Aug 16 '21 at 21:13

0 Answers0