'How to run nodejs with html like vanilla js
I am very new to node so I need help with this one. I understand how to display a html file using nodejs such as this:
(node)
var http = require('http');
let fs = require("fs");
http.createServer(function (req, res) {
fs.readFile("test.html",(err, data) => {
if(!err) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
}
});
}).listen(8080);
However, I want to know how I would use this to do things you would do in js such as
(js)
document.getElementById("thisElement").style.backgroundColor = "#234";
document.getElementById("thisElement").addEventListener("click",() => {
doThings();
});
And other related js stuff.
Solution 1:[1]
You see this line on your codes
fs.readFile("test.html",(err, data) => {
this line goes and pick test.html file, which is available on your client side now, anything relating to this test.html file is a client thing since its html, in it you will declare tags and javascript file references as below
<html>
<body>
<script src = "../../to/js/files.js"></script>
<!-- or as below -->
<script>
//now in here you get to do your fun stuffs as you asked above
document.getElementById("thisElement").style.backgroundColor = "#234";
document.getElementById("thisElement").addEventListener("click",() => {
doThings();
});
</script>
</body>
</html>
Solution 2:[2]
I don't think you can do it on this way with node because it's not its purpose, node was made to serve things not to change html or act on browser stuff as you want, there's no DOM on node.
BUT, You can try reading the file and editing it inserting content, but it will be such an hard thing to do once you will need to change the text and it will probably being an array or you can try it with express termplate engine, you can use templates that are mutable when you serve it with node, so you can use variables as html values.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ndotie |
| Solution 2 | Gabriel Panegrossi Santos |
