Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include CSS and JS files in Node.js

Tags:

html

css

node.js

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);
like image 807
user7438259 Avatar asked May 21 '18 01:05

user7438259


1 Answers

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!

like image 56
Lalit Dashora Avatar answered Oct 10 '22 17:10

Lalit Dashora