2016-05-22 71 views
1

我想在瀏覽器中使用Nodejs顯示一個HTML文件。但是,當我運行代碼,我得到了以下錯誤:Nodejs錯誤:'不能讀取屬性isFile()的未定義'

cannot read property isFile() of undefined 

這是我使用的代碼:

var http = require('http'); 
var url = require('url'); 
var path = require('path'); 
var fs = require('fs'); 

var mimeTypes = { 
    "html" : "text/html", 
    "jpeg" : "image/jpeg", 
    "jpg" : "image/jpg", 
    "png" : "image/png", 
    "js" : "text/javascript", 
    "css" : "text/css" 
}; 

var stats; 


http.createServer(function(req, res) { 
    var uri = url.parse(req.url).pathname; 
    var fileName = path.join(process.cwd(),unescape(uri)); 
    console.log('Loading ' + uri); 


    try { 
     stats = fs.lstat(fileName); 
    } catch(e) { 
     res.writeHead(404, {'Content-type':'text/plain'}); 
     res.write('404 Not Found\n'); 
     res.end(); 
     return; 
    } 

    // Check if file/directory 
    if (stats.isFile()) { 
     var mimeType = mimeTypes[path.extname(fileName).split(".").reverse()[0]]; 
     res.writeHead(200, {'Content-type' : mimeType}); 

     var fileStream = fs.createReadStream(fileName); 
     fileStream.pipe(res); 
     return; 
    } else if (stats.isDirectory()) { 
     res.writeHead(302, { 
      'Location' : 'index.html' 
     }); 
     res.end(); 
    } else { 
     res.writeHead(500, { 
      'Content-type' : 'text/plain' 
     }); 
     res.write('500 Internal Error\n'); 
     res.end(); 
    } 
}).listen(3000); 

我得到的錯誤是stats.isFile附近()。我試圖解決這個錯誤。但它不適合我。我需要一些解決這個錯誤的建議。

+0

請勿在此發佈文字圖片。發佈文字。你的標題中已經包含了大部分內容。 – EJP

回答

0

您正在使用錯誤的函數。你應該使用:

stat=fs.lstatSync("your file") 

然後你的代碼應該工作。

fs.lstat("your file",function (err,stats){})

是一個期待回調的異步函數。看看文檔here

1

變量統計信息被設置爲未定義,而不會引發錯誤。發生這種情況是因爲fs.lstat(fileName)返回undefined。

之前的if語句或者可能的,而不是try catch塊,你可能想要做的事,如:

if (!stats) { 
    res.writeHead(404, {'Content-type':'text/plain'}); 
    res.write('404 Not Found\n'); 
    res.end(); 
    return; 
} 
相關問題