Search code examples
javascripthtmlnode.jsnode-serialport

How to execute node function using html button


I'm new at nodejs and I want to write to a serial port using node but now I want it to be triggered by a button. And the data is coming from a textbox. My node script is doing fine when I run it in the console/terminal. But can't do it with a button in a webpage. Here's my nodejs embedded in html

<!DOCTYPE html>
<html>
<head>
    <title>Node x HTML</title>
</head>
<body>

    <script>
    function write_serial() 
    {
        var serialport = require("serialport");
        var SerialPort = serialport.SerialPort;

        var sp = new SerialPort("/dev/ttyACM0", {
          baudrate: 9600,
          parser: serialport.parsers.readline("\n")
        });

            var text = document.getElementById("textbox1").value;

            sp.on('open', function() 
            {
                sp.on('data', function (data) 
                {
                    sp.write(name);
                });
            });
    }

    </script>

    <Input Type = "text" id = "textbox1" >
    <BR>
    <br><button onclick="write_serial();" href="javascript:;">Go!</button>
</body>
</html>

Here's the error I got when I open the console of the page (F12)

ReferenceError: require is not defined

Thanks in advance for your help. :)


Solution

  • Node.js is a hosting environment, that can execute JS and provides Node.js specific API. Browser, is a different hosting environment, with different API's. You can't use Node's specific API in a browser, and JS that uses Node API will result in an error in a browser.

    For example, your script is using global require function, which is not available in a browser API's. And that's why:

    ReferenceError: require is not defined

    Conversely, your script can't be executed on Node as well, since it uses browser API:

    document.getElementById("textbox1")

    You've mixed API's from different environments in one script.

    However, if your JS script doesn't use Node or browser specific API, it can be executed in both Node and a browser without an error. But it's not the case with your script.

    The solution to your problem can be to split your script into two separate scripts, run one in a browser, and the other in Node.js, and to exchange data between them using XMLHttpRequest.