2013-03-16 26 views
0

教程:我想通過localhost打開一個文件,但我不知道我必須在瀏覽器中輸入哪個路徑。是localhost,我的server.js位於哪裏? (對不起,我是新來的編程和節點)node js localhost shal打開一個文件

教程碼

var path = require('path'), 
    fs = require('fs'); 

require('http').createServer(function(req, res) { 
    var file = path.normalize(req.url); 

    console.log(file); 

    path.exists(file, function(exists) { 
    if (exists) { 
     fs.stat(file, function(err, stat) { 
     var rs; 

     if (err) { throw err; } 
     if (stat.isDirectory()) { 
      res.writeHead(403); 
      res.end('Forbidden'); 
     } else { 
      rs = fs.createReadStream(file); 
      res.writeHead(200); 
      rs.pipe(res); 
     } 
     }); 
    } else { 
     res.writeHead(404); 
     res.end('Not found'); 
    } 
    }) 
}).listen(4000); 
+0

這很可能是CWD。 – tjameson 2013-03-16 01:48:56

+0

console.log語句不會輸出它正在查找的文件嗎?此外,服務器正在偵聽端口4000,因此您在瀏覽器中將該應用程序定位爲http:// localhost:4000 – bryanmac 2013-03-16 03:39:33

回答

2

request.url通常爲/something/like/an/absolute/path,除非你從一個HTTP代理客戶端(添加http://...前綴request.url)請求或做出一些自定義HTTP請求。

反正path.normalize只處理... s。 您的代碼將允許任何人訪問您的計算機上的任何文件(可通過運行node進程的帳戶訪問)。

更好/更安全的做法是加入__dirname與解碼request.url並檢查是否解決路徑與絕對路徑開始(與尾隨路徑分隔符)的目錄,你想從提供靜態內容:

var scriptDir = path.resolve(__dirname + path.sep + "static" + path.sep), 
    requestPath = decodeURIComponent(request.url); 
requestPath = path.resolve(path.join(__dirname, "static", requestPath)); 
if (requestPath.indexOf(scriptDir) === 0) { 
    // serve the file 
} else { 
    response.writeHead(403); 
    response.end(http.STATUS_CODES[403]); 
} 

現在如果你要求說,http://localhost:4000/index.html它應該服務於位於/path/to/your/node/app/dir/static/index.html的文件