I am learning how to use Node.js but I'm stuck. I am unable to load css and js files in my project. I am loading Bootstrap and Fontawesome from a CDN and they're rendering fine. As for my own custom css and js, they are not loading at all.
My folder file path:
folder
index.html
app.js
package.json
css
main.css
files
file.pdf
app.js:
var http = require('http');
var fs = require('fs');
//creating server
http.createServer(function (req, res) {
fs.readFile('index.html', function (err, html) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(html);
res.end();
});
}).listen(8080);
I would suggest you create a public directory where you should keep all your javascript, CSS, images etc.
Now in app.js file, you can add this code to make all these files available anywhere in your node.js project.
app.use(express.static(path.join(__dirname, 'public')));
Don't forget to include path and express in your header like this:
var express = require('express');
var path = require('path');
Now you can use your CSS/JS files wherever you want like this.
<link rel='stylesheet' href='/style.css' />
Here style.css is your custom CSS file. Hope this way works fine to you.
HTH Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With