Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

node.js - What is the Error Parameter in The Multer Filename Callback For?

I am using Multer to get files from requests for my Express API, and I am wondering what the purpose of the error value in the filename callback is. Here is my code:

const multerFile = multer({
  storage: multer.diskStorage({
    destination: "uploads/",
    filename: (req, file, callback) => {
      callback(ERROR HERE WHAT IS THIS FOR?, "fileNameHere`); 
    },
  }),
});
question from:https://stackoverflow.com/questions/65891952/what-is-the-error-parameter-in-the-multer-filename-callback-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Node, the way possibly-asynchronous callbacks are typically structured is that the first argument is an error, OR the second argument is the success value. For example, you'll very often see patterns like this:

callSomeAPI((error, result) => {
  if (error) {
    // There was an error, do something with it
    handleError(error);
  } else {
    // Success
    handleResults(result);
  }
});

This filename callback is doing the same sort of thing. If you implement some custom logic and want to indicate that the process failed, pass the first argument containing the reason to the callback:

callback('Desired filename contains invalid characters');

Otherwise, leave the first argument nullish:

callback(null, 'fileNameHere');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...