2012-01-30 46 views
0

昨天我已經玩了一些Node.js和我的第一個想法是使一個簡單的web服務器,加載一個js文件的html頁面這樣:我的node.js簡單的web服務器不能訪問父文件夾

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

和一切正常。

我決定把這個JS腳本在子目錄下,修改行:


... 

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

但path.exists()沒有檢查HTML頁面和其他文件的存在。

你能告訴我什麼是我的錯(我認爲那只是微不足道的改變)?

謝謝。

回答

4

我的猜測是,您正嘗試從父文件夾而不是從子目錄直接運行js腳本。

例如:如果你在目錄foo和你server.js在子目錄bar
然後如果你運行node bar/server.js,然後..將指向foo的父母,而不是酒吧的父母,這就是爲什麼該文件未找到。

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

你可以嘗試cdbar和運行node server.js

或將腳本中的../aPage.html更改爲__dirname/../aPage.html

PS:您可以使用path.resolve來獲取絕對路徑。

+0

謝謝,我沒有意識到,因爲我在我的c9.io項目,我從ide運行節點! – Dario 2012-01-30 11:08:16

相關問題