Nodejs错误:'无法读取属性isFile()的未定义'

我正在尝试使用Nodejs在浏览器中显示一个HTML文件。 但是当我运行代码时,我得到了以下错误:

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()。 我试图解决这个错误。 但这不适合我。 我需要一些解决这个错误的build议。

您正在使用错误的function。 你应该使用:

 stat=fs.lstatSync("your file") 

那么你的代码应该工作。

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

是一个期待callback的asynchronous函数。 看看这里的文档。

variables统计被设置为undefined,而不会引发错误。 发生这种情况是因为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; }