How can I include css files using node, express, and ejs?
Solution 1
Use this in your server.js file
app.use(express.static(__dirname + '/public'));
and add css like
<link rel="stylesheet" type="text/css" href="css/style.css" />
dont need / before css like
<link rel="stylesheet" type="text/css" href="/css/style.css" />
Solution 2
1.Create a new folder named 'public' if none exists.
2.Create a new folder named 'css' under the newly created 'public' folder
3.create your css file under the public/css path
4.On your html link css i.e
<link rel="stylesheet" type="text/css" href="/css/style.css">
// note the href uses a slash(/) before and you do not need to include the 'public'
5.On your app.js include :
app.use(express.static('public'));
Boom.It works!!
Solution 3
For NodeJS I would get the file name from the res.url
, write the header for the file by getting the extension of the file with path.extname
, create a read stream for the file, and pipe the response.
const http = require('http');
const fs = require('fs');
const path = require('path');
const port = process.env.PORT || 3000;
const server = http.createServer((req, res) => {
let filePath = path.join(
__dirname,
"public",
req.url === "/" ? "index.html" : req.url
);
let extName = path.extname(filePath);
let contentType = 'text/html';
switch (extName) {
case '.css':
contentType = 'text/css';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
}
console.log(`File path: ${filePath}`);
console.log(`Content-Type: ${contentType}`)
res.writeHead(200, {'Content-Type': contentType});
const readStream = fs.createReadStream(filePath);
readStream.pipe(res);
});
server.listen(port, (err) => {
if (err) {
console.log(`Error: ${err}`)
} else {
console.log(`Server listening at port ${port}...`);
}
});
Solution 4
The custom style sheets that we have are static pages in our local file system. In order for server to serve static files, we have to use,
app.use(express.static("public"));
where,
public is a folder we have to create inside our root directory and it must have other folders like css, images.. etc
The directory structure would look like :
Then in your html file, refer to the style.css as
<link type="text/css" href="css/styles.css" rel="stylesheet">
Solution 5
Use in your main .js
file:
app.use('/css',express.static(__dirname +'/css'));
use in you main .html
file:
<link rel="stylesheet" type="text/css" href="css/style.css" />
The reason you getting an error because you are using a comma instead of a concat + after __dirname
.
stealthysnacks
Updated on December 19, 2020Comments
-
stealthysnacks over 3 years
I'm trying to follow the instructions to https://stackoverflow.com/a/18633827/2063561, but I still can't get my styles.css to load.
From app.js
app.use(express.static(path.join(__dirname, 'public')));
In my .ejs, I have tried both of these lines
<link rel="stylesheet" type="text/css" href="/css/style.css" /> <link rel="stylesheet" type="text/css" href="/public/css/style.css" />
Neither loads the css. I've gone into the developer's console noticed the type is set to 'text/html' instead of 'text/css'.
My path looks like
. ./app.js ./public /css /style.css
-
mscdex almost 10 yearsThat'll break for non-root paths though (e.g. hitting
/article/edit
will result in the browser looking for/article/css/style.css
). -
FernandoZ over 6 yearsI used let path = path.join(__dirname + '/public'); ... you use let path = require('"path"); to use path.join ... joining them as strings on windows did not work
-
Dylan Landry almost 6 yearsFor more information on serving static files (like stylesheets) using Express.
-
Zgore about 5 yearsThere is a mistake here, you should use the '/' before you path to your .css, otherwise for non-root paths it will not work because the path is not absolute : <link rel="stylesheet" type="text/css" href="/css/style.css" />
-
Nandit Mehra almost 5 yearsincomplete answer.
-
Quentin almost 5 yearsThe approach taken in the accepted answer is more reliable than this. See this question. We know the relationship between the public directory and the directory with the script in it. We don't know the relationship between it and the directory the script was invocked from.
-
Quentin almost 5 yearsThe approach taken in the accepted answer is more reliable than this. See this question. We know the relationship between the public directory and the directory with the script in it. We don't know the relationship between it and the directory the script was invocked from.
-
Jason R almost 4 yearsI came here looking how to get the images that i was setting as a background to be linked correctly. The same method below can be applied to an 'img' folder which can then be linked to normally if they are both in the public folder. Thanks for a great answer!
-
Scott Anderson almost 4 yearsI don't understand why you would write an answer in pure node/JavaScript - the question is specifically about express and how to serve files properly using that library. What you say about the basis of the problem being about HTTP is also wrong, it has nothing to do with separating files. Even if the OP followed your advice they still wouldn't know how to serve files on express which is what they wanted to do
-
J-D3V almost 4 years@ScottAnderson first of all this question has been edited from the original question, but I would agree that the question as it looks in its contemporary state is directed towards Express, through the author never explicitly states it. When writing this I was hoping to help give an understanding of the mechanics under the hood. I feel that is more help than just giving a couple lines of code to person that's obviously very new to Node. If you don't like it down vote it. If the question hits 0 I will remove it. Every JS framework, no matter the flavor, in essence is Vanilla Flavored.
-
Scott Anderson almost 4 yearsThe question has a code line right up the top which talks about app.set (maybe this wasn't there originally). Don't get me wrong I think that understanding this is useful for web programming, but I just don't see how it's relevant to this question given what OP wrote. Anyways after commenting I saw someone answered very similarly: whilst I can't verify I could say that maybe the original question was quite different. If not, however, then IMHO this falls under 'useful knowledge', not 'relevant information' and should be formalised slightly into a blog or gist and linked in the comments only
-
Antonin GAVREL over 3 yearsVery nice, thank you, have been looking for quite some time for something like that.
-
Chinky Sight over 3 years@arunkumar I am new to express, I have a question why do we need to use middle wares like
static
to serve CSS files ? like before studying node and express, I just linked the CSS file to the HTML file and it works fine but not while using express. Why is that ? -
George Mylonas over 2 years
app.use(express.static(path.join(__dirname, 'public')));
+<link rel="stylesheet" href="/css/entypa_pdf.css" />
to include it. Inpublic
folder there must be a foldercss
which resolves to final pathpublic/css
.