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';
            case '.css':
                contentType = 'text/css';

            fs.readFile(filePath, function(error, content) {
                if (error) {
                else {
                    response.writeHead(200, {
                        'Content-Type': contentType
                    response.end(content, 'utf-8');
        else {
            console.log('Something goes wrong ;(');
    console.log('Server running!');
}).listen('8080', '');

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)?


Problem courtesy of: Dario


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.

  |     +----- 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.

Solution courtesy of: qiao

Node.js Recipes责编内容来自:Node.js Recipes (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » My node.js simple web server doesn’t access parent folder

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录