Monday, 15 March 2010

node.js - How to resolve paths in Node -



node.js - How to resolve paths in Node -

i have node server running, , trying figure out how convey paths files on servers (and how respond requests these resources) have static file server, 1 can command based on request parameters (post or get etc.). right file construction set follows (dir_ means directory):

main folder: server.js dir_content: home.html style.css dir_uploads: dir_finished: file1.txt file2.txt

to respond requests, code looks 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 respond get requests web pages right page (if exists) warps path resource on server.

example: trying retrieve file1.txt navigate localhost:8080/dir_content/dir_uploads/dir_finished/file1.txt

but code add together additional ./dir_content request, making trying visit:

localhost:8080/dir_content/dir_content/dir_uploads/dir_finished/file1.txt

is there simpler way provide accurate absolute paths resources in folders without external node modules (by setting sort of base of operations directory somehow)?

at first glance appears aren't accounting request.url perchance including dir_content prefix. if indeed true, recommend simple regular look test see if there:

if (!/^[\/]?dir_content\//i.test(request.url)) filepath = '/dir_content' + request.url; filepath = '.' + filepath;

simple fiddle demonstrate regular expression:

http://jsfiddle.net/97q43/

node.js filepath

No comments:

Post a Comment