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

Accepted answer
Score: 30

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 6 have re-written your code. Notice I do 5 not use case/switch. I prefer much simpler 4 if and else, you can put them back if that's 3 your preference. The url and path modules 2 are not necessary in my re-write, so I have 1 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/');
Score: 8

You might want to look into using server 5 frameworks like express which allow you to set 4 a 'public' directory for automatically routing 3 static files

var express = require('express'),app = express();
app.use(express.static(path.join(__dirname, 'public')));

The cheap overhead of such a 2 framework would really be worth the effort 1 of effectively 'reinventing the wheel'

Score: 2

public does not appear in the URL requested by 2 the client, so the switch on myPath will 1 always fall through.

Score: 1

You could consider looking at the Static middleware 5 provided in Connect. Looking at Static's 4 source code might give you some ideas on 3 how to do this with node.js code (if you 2 want learn how to do it without using an 1 existing library).

Score: 1

Auto Update files on change, delay for update 1 1 sec. Format : app.js | index.htm | style.css

// packages
const http = require('http');
const fs = require('fs');
// server properties
const hostname = '127.0.0.1';
const port = 3000;
const timer = 300;

//should trigger atualize function every timer parameter
let htmlfile = '';
let cssfile = '';
let jsfile = '';

uptodate();

// should read file from the disk for html
function uptodate()
{
  console.log(1);
   fs.readFile('./index.html', function (err, html) {
    if (err) {
      throw err; 
    }       
    htmlfile = html;
  });
  // should read css from the disk for css
   fs.readFile('./style.css', function (err, html) {
    if (err) {
      throw err; 
    }       
    cssfile = html;
  });

  // should read js file from the disk
  fs.readFile('./app.js', function (err, html) {
    if (err) {
      throw err; 
    }       
    jsfile = html;
  });
  setTimeout(function(){ uptodate(); }, 1000);
}
const server = http.createServer((req, res) => {
  res.statusCode = 200;

  // should send css and js
  if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.js'
   res.writeHead(200, {'Content-Type': 'text/css'});
   res.write(cssfile);
   res.end();
   return;
  }
  if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js'
   res.writeHead(200, {'Content-Type': 'text/javascript'});
   res.write(jsfile);
   res.end();
   return;
  }
  // should send html file via request
  res.writeHeader(200, {"Content-Type": "text/html"});  
  res.write(htmlfile);
  res.end();
});

// should send css and js 

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
Score: 0
    // get the extensions of the files inside this dir (.html, .js, .css)
    var extname = **mypath**.extname(path);

These are reversed. Should be:

   var extension = path.extname(mypath);

I also do 2 not use function names for variable names 1 when I can avoid it.

More Related questions