How to run nodejs with html like vanilla js - javascript

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.

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).

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>

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.
https://expressjs.com/en/resources/template-engines.html

Related

How to read javascript file in frontend javascript/browser

Please read carefully before marking as dupe.
I want to read a javascript file on frontend. The javascript file is obviously being used as a script on the webpage. I want to read that javascript file as text, and verify if correct version of it is being loaded in the browser. From different chunks of text in the js file, I can identify what version is actually being used in the end user's browser. The js file is main.js which is generated by angular build.
I know we can do something like creating a global variable for version or some mature version management. But currently, on production site, that will mean a new release, which is couple of months from now. Only option I have right now is html/js page, which can be directly served from production site, without waiting for new release.
So my question is, is it possible we can read a javascript file as text in hmtl/js code in the browser.
an idea can be :
use fetch api to get a container that can be use to async load the script
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
use text() method which return a promise to get text content
fetch('http://localhost:8100/scripts.js').then((res) => res.text()).then(scriptContent => {
// scriptContent contain the content of your script
// if (scriptContent.includes('version : 1.1.1')
console.log(scriptContent);
});
this is absolutely not an efficient way, but since you want to work without any new version release or working with a version management system
here is the thing
assume file's checksum (md5 sha125 or anything) of V1.0 equals X and you will calculate before the coding part.
if checksum(X) != X{
location.reload()
}
would help for a security features too since it's an important project.
another way of controlling this situation is changing the main.js file's name if it is possible.

Importing javascript into html inline script for single file usage

I am working on node express server which generates reports (tables, charts) for data stored in database (MongoDB). What makes it hard is that the report should be downloadable as a single file and viewable offline. Which means that all the data and javascript should be inside the html file.
By searching stackoverflow I found this question - Inline CSS/Javascript into a HTML file. One of the solutions is command-line tool which visits the page and bundles together all assets, other solutions use other languages. In my case it doesn't make sense to visit the page and download the files as they are already in memory and should be imported from node server.
So here is example of how I've been doing it so far.
Server.js:
// Templating library
const mustache = require("mustache");
// Javascript to be imported into html as inline script
const someFunction = require("./src/someFunction.js").toString();
app.get("/:id", async (req, res) => {
// Get data from DB
const data = await MongooseSchema.find({ id: req.params.id });
// Read html view
const view = fs.readFileSync("./views/report.html", "utf8"});
// Render with mustache
const html = mustache.to_html(view, {
data,
javascript: { someFunction }
});
// Send rendered html
res.send(html);
});
And report.html includes this script tag:
<script>
const data = {{{data}}};
{{{javascript.someFunction}}}
</script>
I am importing javascript files as strings and then rendering them inside the html file using mustache templating library. This approach seems kind of hacky, there should be a better way.
Also I am thinking about implementing some bundler (webpack/parcel/rollup) to combine all the js files into one which I could then manually import into html as inline script.
And maybe even use some framework like react to make my life easier.
So my question is, is this approach viable? Are there any better ways to do this?

How to load my css and js files with node.js [duplicate]

This question already has an answer here:
How to include css and js files in Node.js project
(1 answer)
Closed 4 years ago.
I have looked at a lot of similar questions but I can't get it to work, so I'll just ask it myself
I have a folder like this:
Source Code
Frondend
Graphs.html
Graphs.css
Temperature.js
Server_Backend
server.js
I want to run these file with node.js, I can also use express if necessary.
I have this in server.js to load my html:
fs.readFile('../Frondend/Graphs.html', function (err, html) {
if (err) throw err;
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8080);
});
these are the links in my html header:
<script type="text/javascript" src="Temperature.js"></script>
<link rel="stylesheet" type="text/css" href="Graphs.css">
How do I also include my css and js file? As I said I tried a lot of things already but I can't seem to get it to work.
So what the browser will do, after you send the html (which you do perfectly), it will look for http://yourdomain.com/Temperature.js and http://yourdomain.com/Graphs.css. To allow express to expose these to the browser, express has the express.static function.
You can do, when using express, is
app.use(express.static('./Frondend'));
This will take any request to your website, and will check if there is a file in the Frondend folder, and if so, will send that file.
Hope that makes sense :)
since you are a beginner, I would use express.js. It makes it much easier to deal with things like static assets (css and javascript files) and helps you with routing requests to different code parts (like /users, /files, /about)
To solve your question, best would be to look at following information from express.js about static files after you looked at the getting started guide

Read data from text file in javascript

I'm trying to make a complex website, and I want to split it into multiple files, one of them is the content itself, and for that I want to make a function that changes a div content from the file.
The entire code :
<html>
<body onLoad = "uploadData();">
<div id = "text"> </div>
</body>
<script>
function uploadData()
{
var file = new File("data");
file.open("r");
var data = "";
while (!file.eof) {
data += file.readln() + "\n";
}
file.close();
alert(data);
document.getElementById('text').innerHTML = data;
}
</script>
</html>
The code has an error at line 7.
Please help me !!!
You cannot read from a file this way in a modern browser for security reasons (the scripts are sandboxed).
Maybe you took those functions from a very old and non-standard Javascript reference like JavaScript Programmer's Reference (by Cliff Wootton, 2001) or Pure JavaScript
(by Charlton Ting, Jason Gilliam, Allen R. Wyke, 1999). Those are very antique manuals and deal with obsolete browser versions (Internet Explorer 4...).
You can also find those functions or a similar set in the APIs provided by JS engines like Adobe InDesign, NodeJS or ShellJS, which are not browser engines. Working with a JS engine doens't imply you'll find the same API as provided by another one. Typically, you won't do the same things with NodeJS and Firefox JS engine (OdinMonkey currently).
If you want to dynamically change the content of your page (ie its DOM structure) with an external resource (a file located in your server), use the Ajax techniques.
Finally, in this SO question, you'll find some ways to get the content of a local file, but they must have been selected manually by the user.
If you are creating a complex website, you need a web server. Let's assume your content does not need server side rendering and you have Apache installed, then a plain XHR function can help you fetching the content. If plain XHR is not helpful, jQuery perhaps can ease things.

List files in website directory without index.html

If a directory on a webserver doesn't have any html files (e.g. index.html), then when you navigate to that url, typically you just see a list of the files in that directory (unless .htaccess was changed to prevent this). Is it possible to get a list of these files in javascript?
you can do it with a get_files function
var files;
function getFilesInFolder(folderServerRelativeUrl) {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var folder = web.getFolderByServerRelativeUrl(folderServerRelativeUrl);
files = folder.get_files();
context.load(files);
context.executeQueryAsync(Function.createDelegate(this, this.OnSuccess), Function.createDelegate(this, this.OnFailure));
}
Any time you write code to display something on the web, you are using a server-side language. HTML is a server-side language, but has extremely limited programming capabilities - can't read the server file system, cannot loop, etc.
So, to do what you are asking you need a server-side language. Either PHP or node.js or Python etc. Almost all webhosts already include PHP, but you can now find some (a2, webhostpython) with the other two. There are TONS of tutorials online for doing what you want with PHP. Tons.
So, to be clear, if you want to code your server-side in javascript, you need to have node.js installed on that server. To use PHP, it's almost certainly already there.
PHP files are identical to HTML files, except they end in .php instead of .html, which allows them to process PHP code between the <?php and ?> tags. Generally, PHP files are either pure PHP-only, OR they are a mix of HTML and PHP, with the PHP code included on the page between these tags.
Here is a basic tutorial to give you an idea how it would work:
https://daveismyname.blog/creating-an-image-gallery-from-a-folder-of-images-automatically
What you can do is create an endpoint that would point out all the files that you need to display and make an API call to the endpoint using JS

Categories