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

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

Related

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

XHRs from an outside js file makes app crash

I have an api.js file where I make a couple of XHR-equests. I was using it inside a script tag inside an .ejs file, but it was getting too crowded. So after I moved everything to the api.js I'm no longer able to access its data.
Every time I try to require it from my app.js my program crashes.[nodemon] app crashed - waiting for file changes before starting... I've tried putting it inside my public folder and some other places, but it never works.
Should I export the data from api.js like I would if it was a data schema? If so, how would I do that? (something like module.exports = mongoose.model("Data", dataSchema); ? I don't have any models in api.js, it's just a couple of requests)
The .ejs file that is supposed to make use of api.js has a route like this:
app.get('/home', function(req, res){
res.render('home', { moment: moment }); //home is an .ejs file
});
The { moment: moment } is from moment.js.,.if I'm supposed to export api.js, how could I use it in this route since I'm already using moment.js. I think I can't just do
res.render('home', { moment: moment }, {api: api});
The main problem might be the app crashing since without solving this issue I won't be able to solve anything else.
Any help is appreciated. Thanks!
I'm not sure how much of the process you understand, but your ejs file is a "template" --- you pass "variables" to it and "render" it, and then express sends the html file. After it renders it, the "variables" are no longer accessible unless they're passed into a <script> tag like you might be doing. (I'm not sure how you're using moment --- or maybe you only use moment to render something server side)
Instead of trying to pass api, your html file can use the script tag, which can refer to other files like
<script src='/js/api.js'></script>
But your server (through express.js) needs to serve this file.
That is the common option, and should work for you.
You generally don't "pass" a module or library to the template engine unless you need it to render something. But if you wanted to, you can also read the api.js file as a string and "inject" it into the script tag... (I don't usually see it done this way)
<script><%= api %></script>

meteor: split code into its own file

I started with a meteor project and I noticed that code is growing rapidly.
The stuff that goes inside
if (Meteor.isClient) { .... }
is getting big now. Its all Template.box...., Template.bar...., etc code, so I think it could be placed into its own file. Is this possible ?
Yes, they should be placed in their own files and you should put your isClient code under the client directory and your isServer code under the server directory. The examples each use a single .js file because it makes it easy to read when you are only dealing with a few lines of code. However, that isn't how you should build a large project.
Typically your client code would be broken out by view or url path into files where each is responsible for a single template or a collection of a few related templates. For more ideas see the unofficial-meteor-faq.

how can I modify or replace the directory index page in Express?

In express, I can something like this to have a static server, with directory index pages:
app.configure(function() {
app.use('/mystuff', _express.static(__dirname + "/whatever/stuff"));
app.use('/mystuff', _express.directory(__dirname + "/whatever/stuff"));
});
I would like to modify the directory index pages, by giving them different css, adding some javascript, and maybe altering the html. I prefer use as much of the existing functionality if possible, but if it is easy to just replace the whole directory middleware with my own code, that's an option. Not sure where to start with this. Of course, I don't want to actually edit code in the express or connect modules.
BTW, one reason for this is to workaround a bug I mentioned here: How do I set up static serving in Express with an arbitrary start path?
As you said in your comment, the express.directory functionality comes from Connect middleware; however, there doesn't seem to be a way to set a custom file.
As an alternative solution, you could fork Connect, change the files (located at lib/public/directory.html and lib/public/style.css), use your fork as a dependency, and do:
var connect = require('connect');
app.configure(function() {
app.use('/mystuff', connect.static(__dirname + "/whatever/stuff"));
app.use('/mystuff', connect.directory(__dirname + "/whatever/stuff"));
});
Instead of the express ones. I just tested this (by editing the files in node_module), and it worked.
EDIT:
Actually, you could probably just grab directory.js from connect and modify it and put it in your app and require() it, and then use yours instead. I haven't tested this, but I can't see why it wouldn't work.

modrewrite for css / jss minified

I have a web site hosted in a CentOS 5-Plesk-Apache server. I have recently added a second site to the server for serve dynamic content. I have established rewrite rules for images (static content) that works pretty well. The module rewrites the URI in the static server to pointing to the the original file.
The problem is that the first site has the minify (http://code.google.com/p/minify/) script installed but i cannot realize how to write a modwrite rule that works, so if I have:
...
< style src='http://www.mystaticserver.com/min/f=style.css' >
...
somewhere, this becomes in the file with this URL
http://www.myserver.com/min/f=style.css
Any ideas? Thank you in advance
PS: I asked this question in serverfault but i don't get any answers
What are the redirect rules you are trying to use in the .htaccess file?
If you are sending the request to a different server, are you using redirectmatch?
Also, if you are including a query string you may need to apply the option [QSA] to the end to the rule to include it.
Thaks to the guys at serverfault.com... This is the answer:
https://serverfault.com/questions/64223/modrewrite-for-css-jss-minified/65843#65843

Categories