1

Over my nodejs application I have the following functions:

    const special_handle= function(err){
         console.error("Special Handled",err);
    }

    const normal_handle= function(err){
         console.error("Normal Handled",err);
    }

    const callback = function(err,mime,data){
       if(err) {
           if(/*file does not exist*/){
                 return special_handle(err);
           } else {
                  return normal_handle(err);
           }
       }
    }

    fs.readFile(fileFullPath,(err,data)=>{
        if(err){
           return callback(err);
        }

        const mimeType = mime.lookup(fileFullPath);
        callback(null,mimeType,data);
    });

What I want it when the file does not exist to do a special handling instead of do the normal one. But how I will know that the file does not exist over my callback?

1 Answer 1

1

If the file/directory doesn't exist, you will get an ENOENT error. You can then use a switch or if clauses to handle different results.

A typical err object returned by a file/directory that doesn't exist will look like:

{ Error: ENOENT: no such file or directory, open 'test.js' errno: -2, code: 'ENOENT', syscall: 'open', path: 'test.js' }

So if you want to check whether the file exists, you could do:

if (err.code === 'ENOENT') {
  return special_handle(err)
} else {
  return normal_handle(err)
}

or if you want to check for multiple types of errors, such as EPERM which will be thrown when your program doesn't have permission to read the file/directory, you could use a switch-clause:

switch (err.code) {
  case 'ENOENT':
    return special_handle(err)
  case 'EPERM':
    return eperm_handle(err)
  case default:
    return normal_handle(err)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.