Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - external JS and CSS files (just using node.js not express)

Tags:

Im trying to learn node.js and have hit a bit of a roadblock.

My issue is that i couldn't seem to load an external css and js file into a html file.

GET http://localhost:8080/css/style.css 404 (Not Found)  GET http://localhost:8080/js/script.css 404 (Not Found)  

(this was when all files were in the root of the app)

I was told to somewhat mimic the following app structure, add a route for the public dir to allow the webserver to serve the external files.

my app structure is like so

domain.com   app/     webserver.js    public/     chatclient.html      js/       script.js      css/       style.css 

So my webserver.js script is in the root of app, and everything I want to access is in 'public'.

I also saw this example that uses path.extname() to get any files extentions located in a path. (see the last code block).

So I've tried to combine the new site structure and this path.extname() example, to have the webserver allow access to any file in my public dir, so I can render the html file, which references the external js and css files.

My webserver.js looks like this.

var http = require('http') , url = require('url') , fs = require('fs') , path = require('path') , server;  server = http.createServer(function(req,res){    var myPath = url.parse(req.url).pathname;      switch(myPath){        case '/public':          // get the extensions of the files inside this dir (.html, .js, .css)         var extname = mypath.extname(path);            switch (extname) {              // get the html             case '.html':               fs.readFile(__dirname + '/public/chatclient.html', function (err, data) {                 if (err) return send404(res);                 res.writeHead(200, {'Content-Type': 'text/html'});                 res.write(data, 'utf8');                 res.end();               });             break;              // get the script that /public/chatclient.html references             case '.js':               fs.readFile(__dirname + '/public/js/script.js', function (err, data) {                 if (err) return send404(res);                 res.writeHead(200, { 'Content-Type': 'text/javascript' });                 res.end(content, 'utf-8');                 res.end();               });             break;              // get the styles that /public/chatclient.html references             case '.css':               fs.readFile(__dirname + '/public/css/style.css', function (err, data) {                 if (err) return send404(res);                 res.writeHead(200, { 'Content-Type': 'text/javascript' });                 res.end(content, 'utf-8');                 res.end();               });           }           break;            default: send404(res);         }     }); 

Inside the case of public, I'm trying to get any of the folders/files inside of this dir via var extname = mypath.extname(path); Similar to the link I provided.

But at the moment 'extname' is empty when I console log it.

Can anyone advise what I might need to add or tweek here? I'm aware this can be done easily in Express, but I would like to know how to achieve the same thing just relying on Node.

I's appreciate any help on this.

Thanks in advance.

like image 238
Denim Demon Avatar asked Aug 26 '12 22:08

Denim Demon


People also ask

Can we use NodeJS without Express?

It's possible to use NodeJS alone. But, you have to write more code that is provided by express or any other framework.

How do I pass a CSS file in NodeJS?

Css files will be stored in public folder. const http = require('http'); const path = require('path'); const express = require('express'); const bodyParser = require('body-parser'); const route = require('./routes'); const app = express(); app. use(bodyParser. urlencoded({extended: false})); app.

What is the advantage of using external js and CSS files?

The first major benefit of using external CSS style sheets and external JavaScript files is faster load times for your web pages. According to an experiment at Google, even a half a second difference in page load time can make a 20% difference in how much traffic that pages retain.


1 Answers

There are several problems with your code.

  1. Your server is not going to run as you have not specified a port to listen from.
  2. As Eric pointed out your case condition will fail as 'public' does not appear in the url.
  3. Your are referencing a non-existent variable 'content' in your js and css responses, should be 'data'.
  4. You css content-type header should be text/css instead of text/javascript
  5. Specifying 'utf8' in the body is unnecessary.

I have re-written your code. Notice I do not use case/switch. I prefer much simpler if and else, you can put them back if that's your preference. The url and path modules are not necessary in my re-write, so I have removed them.

var http = require('http'),     fs = require('fs');  http.createServer(function (req, res) {      if(req.url.indexOf('.html') != -1){ //req.url has the pathname, check if it conatins '.html'        fs.readFile(__dirname + '/public/chatclient.html', function (err, data) {         if (err) console.log(err);         res.writeHead(200, {'Content-Type': 'text/html'});         res.write(data);         res.end();       });      }      if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js'        fs.readFile(__dirname + '/public/js/script.js', function (err, data) {         if (err) console.log(err);         res.writeHead(200, {'Content-Type': 'text/javascript'});         res.write(data);         res.end();       });      }      if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.css'        fs.readFile(__dirname + '/public/css/style.css', function (err, data) {         if (err) console.log(err);         res.writeHead(200, {'Content-Type': 'text/css'});         res.write(data);         res.end();       });      }  }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); 
like image 181
saeed Avatar answered Sep 30 '22 15:09

saeed