Dario
Dario

Reputation: 5333

My node.js simple web server doesn't access parent folder

yesterday i've played a little with Node.js and my first idea is making a simple web server that load an html page with some js files in this way:

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');

and everything works.

I decided to put this js script in a subdirectory, modify the lines in:


...

var filePath = path.join('..', request.url);
    if (filePath === '../') {
        filePath = '../aPage.html';
    }
...

but path.exists() fails to check the existence of html page and others files.

Could you please tell me what's my fault (I thought that was only that trivial change)?

Thanks.

Upvotes: 0

Views: 1558

Answers (1)

qiao
qiao

Reputation: 18219

My guess is that you are trying to directly run the js script from the parent folder instead of from the subdirectory.

for example: if you are in directory foo and your server.js is in subdir bar,
then if you run node bar/server.js, then .. will point to the parent of foo, instead of parent of bar, that's why the file is not found.

foo
  +---bar
  |     +----- server.js
  +---- aPage.html

You may try to cd into bar and run node server.js.

or change the ../aPage.html in the script to be __dirname/../aPage.html.

PS: you can use path.resolve to get the absolute path.

Upvotes: 4

Related Questions