I am writing a chat-room code which uses the npm module http to create a http server and serve a web page and mosquitto to transfer the data. But I am unable to get my javascript code to work with the html. This is my html code
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{
background-color: black;
}
.inp{
background-color: black;
color: yellow;
width: 500px;
height: 90px
}
.hld{
width: 400px;
height: 60px;
}
</style>
<title>
Gobal Chats
</title>
</head>
<body>
<div class="hld">
<input id="tpc" type="text" style="height: 50px; background-color: yellow; color: black; font-size: 25px; border: 2px solid gold" placeholder="enter topic here"><br><br>
<button onclick="conn()">Connect</button>
<input type="text" style="height: 50px; background-color: orange; color: black; font-size: 25px; border: 2px solid gold" placeholder="enter username here" onchange="setName(this.value)"><br><br>
</div><br><br><br><br><br><br>
<div class="hld">
<input type="text" id="msg" class="inp" placeholder="Type your message here" maxlength="300"></input>
<button onclick="sendMsg()">Send</button>
</div><br><br>
<div id="messages"></div>
</body>
</html>
and this is my Javascript code
var fs = require('fs');
var http = require('http');
var content = "";
fs.readFile("./index.html", function read(err,data){
if(err) throw err;
content = data;
console.log(data.toString())
});
http.createServer(function(req,res){
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write(content);
res.end();
}).listen(8080,'127.0.0.1');
var mqtt = require('mqtt');
var client = mqtt.connect("mqtt://test.mosquitto.org");
var topic = "";
var name = "";
client.on('connect',function(){
client.subscribe(topic);
console.log('subscribed')
})
function conn(){
topic = document.getElementById('tpc').value;
}
function sendMsg(){
var mss = document.getElementById('msg').value;
client.publish(mss);
}
function setName(a){
name = a;
}
console.log("server ready")
But when I run the code and access the webpage on the browser, I get errors saying that the functions I have written cannot be defined such as
Uncaught ReferenceError: conn is not defined
where conn is one of the functions. This means that the html code is not accessing the Javascript code. I cannot put the Javascript code within the <script>
tags of html as mqtt,http and fs are node modules. So how can I get the html code to access the Javascript code?