昨天我玩了一下 Node.js,我的第一个想法是制作一个简单的 Web 服务器,以这种方式加载带有一些 js 文件的 html 页面:
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页面和其他文件是否存在。
你能告诉我我的错是什么吗(我以为这只是一个微不足道的改变)?
谢谢。
最佳答案
我的猜测是,您尝试直接从父文件夹而不是子目录运行 js
脚本。
例如:如果您位于目录 foo
中,并且您的 server.js
位于子目录 bar
中,
那么如果你运行node bar/server.js
,那么..
将指向foo的父级,而不是bar的父级,这就是找不到文件的原因。
foo
+---bar
| +----- server.js
+---- aPage.html
您可以尝试cd
进入bar
并运行node server.js
。
或将脚本中的../aPage.html
更改为__dirname/../aPage.html
。
PS:可以使用path.resolve
获取绝对路径。
关于javascript - 我的 Node.js 简单 Web 服务器无法访问父文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9061778/