yesterday i’ve played a little with Node.js and my first idea is making a simple web server that load an html page with some js files in this way:
var http = require('http'),
fs = require('fs'),
path = require('path');
http.createServer(function(request, response) {
console.log('request starting for: ' + request.url);
var filePath = path.join('.', request.url);
if (filePath === './') {
filePath = './aPage.html';
}
path.exists(filePath, function(exists) {
if (exists) {
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, {
'Content-Type': contentType
});
response.end(content, 'utf-8');
}
});
}
else {
console.log('Something goes wrong ;(');
response.writeHead(404);
response.end();
}
});
console.log('Server running!');
}).listen('8080', '0.0.0.0');
and everything works.
I decided to put this js script in a subdirectory, modify the lines in:
...
var filePath = path.join('..', request.url);
if (filePath === '../') {
filePath = '../aPage.html';
}
...
but path.exists() fails to check the existence of html page and others files.
Could you please tell me what’s my fault (I thought that was only that trivial change)?
Thanks.
My guess is that you are trying to directly run the
jsscript from the parent folder instead of from the subdirectory.for example: if you are in directory
fooand yourserver.jsis in subdirbar,then if you run
node bar/server.js, then..will point to the parent of foo, instead of parent of bar, that’s why the file is not found.You may try to
cdintobarand runnode server.js.or change the
../aPage.htmlin the script to be__dirname/../aPage.html.PS: you can use
path.resolveto get the absolute path.