NicLovin
NicLovin

Reputation: 355

How to get input from a barcode scanner in a Node.js web application?

I would like for my web application (created using node.js express.js and EJS) to be listening for input from a barcode scanner at all times and to perform an action when it receives the input.

I'm assuming the best bet is to use JavaScript to create a listener with a handler that will create an HTTP request when it is called, I'm just stuck on how to create the listener and read in data from the barcode scanner in the background of the web application (I don't want to use html forms to get the data from the barcode scanner, I just want to perform an action such as an HTTP GET request when the input is received).

Upvotes: 1

Views: 2095

Answers (1)

NicLovin
NicLovin

Reputation: 355

Following @Quentin's advice to use addEventListener I found the solution to my problem to be (The scanner input ends with the Enter character so I used that to capture the whole string):

<script>
   var str = '';
   document.addEventListener("keypress", function(e){
      if(e.key == "Enter") {
         console.log(str);
         var temp = str;
         str = '';
         window.location = ('/httpreq?parameter='+temp);
      } else {
         str += e.key;
      }
   });
</script>

Upvotes: 2

Related Questions