Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js : get css file with html render

Tags:

node.js

How can I include a CSS file in my HTML file with a HTML render in Node.js?

Here's what I do:

<link rel="stylesheet" type="text/css" href="./general.css" />

And then is the error when I'm going to localhost:8333/general.css:

Cannot GET /general.css

My module renderer script is the following:

app.set('views', __dirname);
app.engine('html', engines.mustache);
app.set('view engine', 'html');

How should I do it?

like image 339
Cxodael Avatar asked Apr 19 '13 19:04

Cxodael


1 Answers

You can to use Express' static middleware to serve static files like (client-side) JS and CSS:

app.use(express.static());

That will, by default, try and find static files in ./public (relative to the script you configure the middleware from):

yourproject/app.js   <-- if configured here
yourproject/public/  <-- it will look here

If you use this in your HTML/template:

<link rel="stylesheet" type="text/css" href="/css/general.css" />

The middleware will find and (if found) serve ./public/css/general.css.

If you want a setup where your CSS files are in the same directory as your application script, you can tell the middleware where to look for files by passing a directory as first argument:

app.use(express.static(__dirname));
like image 102
robertklep Avatar answered Oct 25 '22 01:10

robertklep