Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

NodeJS is a non-browser JavaScript environment. You can't use most NodeJS features in a browser environment, because they aren't designed for it.

Instead, you'd have a local NodeJS process providing a web endpoint (e.g., a web server; perhaps using Express, but you don't have to) and run that NodeJS process so it's listening for web requests. Then you'd have a button on your web page that makes an ajax call to the NodeJS server, which performs the work.

Naturally, this would only allow you to perform the work on the machine where the server process is running.

Solution 3:

Maybe import the serialport module from https://wzrd.in/standalone/serialport@latest

In other hand, try to seperate the logic from the view, i don't know if your app will grow or if it's just a POC, but use a messageBroker or sockets to bind your actions'view with the engine ?

Hope it helps

Post a Comment for "How To Execute Node Function Using Html Button"