Skip to content Skip to sidebar Skip to footer

Loading Html Stylesheets In Node.js

I am a beginner in node.js, I am learning it at w3schools. Recently, when I was learning File System, I came accross fs.readFile method. As its first argument, I provided it with a

Solution 1:

You probably shouldn't have spaces in your filename, but that's besides the point. What it seems like you want to do is serve a static file.

Since you're already doing this

app.use(express.static(path.join(__dirname, '/public')));

Then just this line is fine. Remove the entire http.createServer method and it should work fine.

href='/css/CSS Transitions - timing function.css'

No need to mess around with fs at all.

EDIT

I think the preferred method of doing this with express is what I wrote above, but maybe changing the header type from text/html to text/css would also work?

Solution 2:

Why you use express and http modules at same time? Already express module wrapped by http module. So you can use express module instead of http. Here, example for use express module.

// proper way in server.jsvar fs = require('fs');
var fs = require('express');
var fs = require('path');

var app = express();

app.use('/app', function(req, res){
    res.sendFile(path.resolve(__dirname, './html/app.html')); // put your app.html's relative path
})

app.use('/app.js', function(req, res){
    res.sendFile(path.resolve(__dirname, './js/app.js')); // put your app.js's relative path
})

app.use('/app.css', function(req, res){
    res.sendFile(path.resolve(__dirname, './css/app.css')); // put your app.css's relative path
})

app.listen(9090, function(err){
    if(err) console.log(err);
    console.log('listening at http://localhost:9090/app');
})

// app.html

<html>
     <head><scriptsrc='/app.js'/><linkhref='/app.css'/></head><body>
          // your elements
     </body>
</html>

Post a Comment for "Loading Html Stylesheets In Node.js"