Reputation: 734
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.
Upvotes: 21
Views: 70585
Reputation: 526
Auto Update files on change, delay for update 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}/`);
});
Upvotes: 0
Reputation: 41
// 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 not use function names for variable names when I can avoid it.
Upvotes: 0
Reputation: 6304
You might want to look into using server frameworks like express which allow you to set a 'public' directory for automatically routing static files
var express = require('express'),app = express();
app.use(express.static(path.join(__dirname, 'public')));
The cheap overhead of such a framework would really be worth the effort of effectively 'reinventing the wheel'
Upvotes: 8
Reputation: 3923
There are several problems with your code.
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/');
Upvotes: 32
Reputation: 2925
You could consider looking at the Static middleware provided in Connect. Looking at Static's source code might give you some ideas on how to do this with node.js code (if you want learn how to do it without using an existing library).
Upvotes: 1
Reputation: 97691
public
does not appear in the URL requested by the client, so the switch on myPath will always fall through.
Upvotes: 2