[英]How to resolve paths in Node
I have a node server running, and I am trying to figure out how to convey the paths to files on my servers (and how to respond to get requests for these resources) so that I basically have a static file server, but one that I can control based on request parameters ( POST
or GET
etc.). 我有一个正在运行的节点服务器,我试图弄清楚如何在服务器上传递文件路径(以及如何响应对这些资源的请求),以便使我基本上拥有一个静态文件服务器,但是我却拥有一个静态文件服务器。可以根据请求参数(
POST
或GET
等)进行控制。 Right now my file structure is set up as follows ( dir_
means directory): 现在,我的文件结构设置如下(
dir_
表示目录):
Main Folder:
server.js
dir_content:
home.html
style.css
dir_uploads:
dir_finished:
file1.txt
file2.txt
To respond to my requests, my code looks like the following: 为了响应我的请求,我的代码如下所示:
http.createServer(function(request, response) {
if(request.method.toLowerCase() == 'get') {
var filePath = './dir_content' + request.url;
if (filePath == './dir_content/') {
filePath = './dir_content/home.html';
}
fs.exists(filePath, function (exists) {
if (exists) {
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');
}
})
This allows me to respond to any GET
requests for web pages with the correct page (if it exists) but it eventually warps the path to a resource on my server. 这样,我就可以使用正确的页面(如果存在)来响应对Web页面的任何
GET
请求,但是最终它会扭曲服务器上资源的路径。
Example: Someone trying to retrieve file1.txt would navigate to localhost:8080/dir_content/dir_uploads/dir_finished/file1.txt
示例:尝试检索file1.txt的用户将导航到
localhost:8080/dir_content/dir_uploads/dir_finished/file1.txt
but my code would add the additional ./dir_content
to their request, making it look like they were trying to visit: 但是我的代码会将额外的
./dir_content
添加到他们的请求中,使他们看起来像在尝试访问:
localhost:8080/dir_content/dir_content/dir_uploads/dir_finished/file1.txt
Is there a simpler way to provide accurate absolute paths to resources in folders WITHOUT external node modules (by setting a sort of base directory somehow)? 有没有一种简单的方法可以为文件夹中的资源提供准确的绝对路径而无需外部节点模块(通过某种方式设置某种基本目录)?
At first glance it appears you aren't accounting for the request.url possibly including the dir_content prefix. 乍一看,您似乎并没有考虑request.url可能包含dir_content前缀。 If that is indeed true, then I would recommend a simple regular expression test to see if it is there:
如果确实如此,那么我建议您使用一个简单的正则表达式测试来查看它是否存在:
if (!/^[\/]?dir_content\//i.test(request.url))
filePath = '/dir_content' + request.url;
filePath = '.' + filePath;
Simple fiddle to demonstrate the regular expression: 简单的小提琴来演示正则表达式:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.