0

I am trying to set up ws but I am getting this error: "Uncaught ReferenceError: require is not defined" & "Uncaught ReferenceError: Cannot access 'ws' before initialization". I use node.js.This is the code:

const WebSocket = require('ws');

const serverAddress = "ws://127.0.0.1:5000";

const ws = new WebSocket(serverAddress);

function send_data(){
  ws.send(document.getElementById("message-input").value);
}

this is the html code:

<input class="input_color" type="text" id="message-input" value="type-here">
<button><input type="image" src="../../img/icon_send.png"id="send-button" alt="submit" 
class="send_button" onclick="send_data() "></button>
<script type="text/javascript" src="../../client.js">
  • you meant `javascript` or `nodejs` in your tags? If `javascript` then `require()` doesn't exist in js. It is a part of Nodejs – ciekals11 Jun 28 '21 at 11:40
  • Are you running it in terminal via `node filename.js` or just open this file in browser? – ciekals11 Jun 28 '21 at 11:44
  • @ciekals11 i use git bash to run it –  Jun 28 '21 at 11:45
  • The first part of code that you posted is in `client.js` file. Am i correct? – ciekals11 Jun 28 '21 at 11:46
  • @ciekals11 yes. –  Jun 28 '21 at 11:47
  • That is your problem. You are including this file as javascript file which is parsed in BROWSER. That is why you have those errors – ciekals11 Jun 28 '21 at 11:48
  • @ciekals11 where should I include it? –  Jun 28 '21 at 11:49
  • summarizing: You have no idea how nodejs works. That is why you have this error. Try some tutorials first and then come back to this question. We can help you with specific problem but in this case we would have to describe to you how nodejs works which is way too much for 1 question. – ciekals11 Jun 28 '21 at 11:50
  • but sine you asked. Here is [how to include files in nodejs](https://stackoverflow.com/a/63567957/9074272) – ciekals11 Jun 28 '21 at 11:52

1 Answers1

1

You are using nodejs code in the browser. The browser doesn’t know ‘require’, so your code will never work like this.

Klaassiek
  • 2,795
  • 1
  • 23
  • 41