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 :
I understand how to display a html file using nodejs such as this:
That does not "display an HTML file using nodejs".
That sends an HTML file to a an HTTP client such as a web browser.
A web browser can display an HTML file.
However, I want to know how I would use this to do things you would do in js such as
Web browsers take HTML, generate a DOM, run JavaScript with client-side Web APIs and provide a UI for the user to interact with it.
Node.js doesn’t.
The JavaScript programming language is a general purpose programming language.
Web browsers provide particular APIs for doing things that are useful to do in a web browser.
Node.js provides APIs for doing things in other contexts (such as running an HTTP server or writing command line utilities).
You can’t take JS designed to run in a web browser and run it in Node. It doesn’t make sense.
(You can write code which runs in both contexts (generating a random number to take a trivial example) but most code isn’t that generic).