Node.js stop working of javascript code
my File structure
app.js
index.html
index.js
app.js
var http = require('http');
var fs = require('fs');
const PORT=80;
fs.readFile('./index.html', function (err, html) {
if (err) throw err;
http.createServer(function(request, response) {
console.log(request.addListener.name);
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(PORT);
console.log(`Server running at http://127.0.0.1/`);
});
index.html
<html>
<head>
<script src="index.js"></script>
</head>
<body>
<button onclick="start()">onclick</button>
</body>
</html>
index.js
function start(){
alert('start');
}
anyone, please suggest me the solution how can I call Javascript function when running on node by clicking the button or change in input data.
A minimal example is given below. I will recommend use third-party
libraries like express-js to create the server.
const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = 8080;
http
.createServer(({ url }, response) => {
response.setHeader("Content-Type", "text/html");
if (url == "/") fs.createReadStream("./index.html").pipe(response);
else {
const filePath = path.join(__dirname, url);
const stats = fs.existsSync(filePath);
if (stats) fs.createReadStream(filePath).pipe(response);
}
})
.listen(PORT);