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.). Right now my file structure is set up as follows ( dir_
means directory):
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.
Example: Someone trying to retrieve file1.txt would navigate to 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:
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. 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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.