This is really weird problem. I just installed Node.JS on my system (Fedora).
I have three files in /var/www/mirror/:
- server.js
- client.js
- index.html
File server.js is the one I call via CLI: node server.js.
It, basically, returns index.html.
var
http = require('http'),
io = require('socket.io'),
fs = require('fs');
http.createServer(function(request, response) {
fs.readFile(__dirname + '/index.html', function(error, data) {
if (error) {
result.writeHead(500);
console.log('Error: Could not read index.html.');
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(data);
});
}).listen(1337, '127.0.0.1');
console.log('Server is running.');
All works as expected and no errors are thrown anywhere.
In index.html I have simple HTML5 structure (nothing unnecessary, really!) and <script /> that points to, already mentioned, client.js.
That line of code looks like this (Ctrl + U; from browser):
<script src="client.js"></script>
By moving cursor on client.js, I got actual location: http://127.0.0.1:1337/client.js.
Seems correct, right?
The problem:
By opening that link it opens wanted file, but the content is as server.js should return.
This disallows me from including any internal scripts and style-sheets!
I guess that anything that goes via http://127.0.0.1:1337/ (also http://127.0.0.1:1337/client.js, http://127.0.0.1:1337/a/b/c etc.) is handled via server.js – and server.js returns index.html (see above).
How can I fix it? Thanks in any advice!
Look at the
req.urlto tell you the url that the user is requesting. From there, you have to have some code decide whether to serve index.html or client.js.Also, since I’m guessing
index.htmlisn’t changing very frequently, you should probably just read it once, and store the buffer in a variable, rather than reading it on every request.There are some modules that make serving static files a bit easier. Check out
filedfor a pretty nice standalone static file