【问题标题】:Node js - Why lstatSync(Path) returns undefined ? - synchronously checkNode js - 为什么 lstatSync(Path) 返回 undefined ? - 同步检查
【发布时间】: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


    【解决方案1】:

    调用res.end() 不会神奇地停止函数的其余部分运行。在catch 处理程序中,您应该从函数显式返回:

    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');
        return res.end();
    }
    

    请注意,HTTP 服务器不对处理程序的返回值做任何事情,因此return res.end() 只是res.end(); return; 的快捷方式。

    【讨论】:

    • 作为单独的语句。 return res.end(); 具有误导性,暗示回调的返回值有任何意义。它没有。 res.end(); return; 避免混淆问题。
    • 谢谢先生,我明白了,但这仍然不能解决lstatSync()的返回值一直未定义的问题
    • @Ashraf 在catch 中添加console.log(e) 以查看引发了哪个错误。很可能,路径 (fileName) 不正确。
    • @robertklep 我做到了,先生,结果甚至很奇怪,这是路径 c:\Users\amt\Desktop\Projects with Node js\index.htm 而不是 C:\Users\amt\Desktop\Projects with Node js\01.simple-web-server\index.htm ,为什么他不能在路径中包含 01.simple-web-server 文件夹? ,他忽略了01.simple-web-server文件夹是怎么回事,为什么会这样?
    • @Ashraf 请求的 URL 到底是什么?
    猜你喜欢
    • 1970-01-01
    • 2021-06-24
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 2020-06-01
    • 2020-09-21
    相关资源
    最近更新 更多