0
昨天我已經玩了一些Node.js和我的第一個想法是使一個簡單的web服務器,加載一個js文件的html頁面這樣:我的node.js簡單的web服務器不能訪問父文件夾
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');
和一切正常。
我決定把這個JS腳本在子目錄下,修改行:
...
var filePath = path.join('..', request.url);
if (filePath === '../') {
filePath = '../aPage.html';
}
...
但path.exists()沒有檢查HTML頁面和其他文件的存在。
你能告訴我什麼是我的錯(我認爲那只是微不足道的改變)?
謝謝。
謝謝,我沒有意識到,因爲我在我的c9.io項目,我從ide運行節點! – Dario 2012-01-30 11:08:16