【发布时间】:2018-03-14 11:04:21
【问题描述】:
我是 Node.js 的新手,我正在尝试创建一个简单的服务器
问题是:
- TypeError: 无法读取未定义的属性“isFile”
到目前为止我做了什么:
- 我尝试了一个简单的调试过程来找出问题的确切位置
- 和我期望的
lstatSync()的返回值中的问题 -
lstatSync()一直返回 undefined ,这是导致isFile()出现问题的原因
注意事项:-
- 我通过在控制台中记录值在传递给
lstatSync()的路径下签入示例代码,结果符合预期 - 另外经过一些研究,我尝试使用
fs.exists(),但我发现它已被弃用! - 最后Docs 并没有提供太多关于函数的信息
示例代码:
var http = require("http"); // creating server
var path = require("path"); // finding the actual path for directories / files
var url = require("url"); // parse url
var fs = require('fs'); // file system core , dealing with files operations
// Array of mime types ..
var mimeTypes = {
'html' : 'text/html',
'css' : 'text/css',
'js' : 'text/javascript',
'jpg' : 'image/jpg',
'png' : 'image/png',
'jpeg' : 'image/jpeg'
}
// creating server ...
http.createServer(function(req , res){
var uri = url.parse(req.url).pathname // parse url , exctract the path after the host name 'incuding /'
var fileName = path.join(process.cwd(),unescape(uri)); // returing current directory path , unescape the url path in case it contains special char.
console.log("data is loading"+uri);
console.log("File name : "+fileName);
var stats;
try {
stats = fs.lstatSync(fileName) // Returns an instance of fs.Stats.
console.log(stats);
} catch (e) {
console.log(stats);
// if the file not exists [NOT FOUND]
res.writeHead(404,{'Context-Type':'text/plain'});
res.write('Error 404 , page not Found \n');
res.end();
}
// file actual path is a file / directory
// file it's a file
if(stats.isFile()){
var mimeType = mimeTypes[path.extname(fileName).split('.').reverse()[0]]; // file name without extension
res.writeHead(200,{'Content-Type':mimeType});
var readStream = fs.createReadStream(fileName);
readStream.pipe(res);
}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(8888);
【问题讨论】:
标签: javascript node.js fs asynchronous