Make node.js not exit on error

前端 未结 7 1947
野的像风
野的像风 2020-12-02 04:42

I am working on a websocket oriented node.js server using Socket.IO. I noticed a bug where certain browsers aren\'t following the correct connect procedure to the server, an

相关标签:
7条回答
  • 2020-12-02 05:43

    Had a similar problem. Ivo's answer is good. But how can you catch an error in a loop and continue?

    var folder='/anyFolder';
    fs.readdir(folder, function(err,files){
        for(var i=0; i<files.length; i++){
            var stats = fs.statSync(folder+'/'+files[i]);
        }
    });
    

    Here, fs.statSynch throws an error (against a hidden file in Windows that barfs I don't know why). The error can be caught by the process.on(...) trick, but the loop stops.

    I tried adding a handler directly:

    var stats = fs.statSync(folder+'/'+files[i]).on('error',function(err){console.log(err);});
    

    This did not work either.

    Adding a try/catch around the questionable fs.statSynch() was the best solution for me:

    var stats;
    try{
        stats = fs.statSync(path);
    }catch(err){console.log(err);}
    

    This then led to the code fix (making a clean path var from folder and file).

    0 讨论(0)
提交回复
热议问题