简体   繁体   English

Node.js触发回调两次,为什么?

[英]Node.js fires callback twice, why?

In the following code, why does the createFile callback fire twice? 在以下代码中,为什么createFile回调两次触发? This only happens when the server (below) is processing two or more requests at the same time, not if only one request has been made. 仅当服务器(以下)同时处理两个或多个请求时才会发生这种情况,而不是仅发出一个请求时。 Output at the bottom of the post. 输出在帖子底部。 The client making the request is not a browser, but another node.js script iterating through a directory and sending a http post request with the file to the server. 发出请求的客户端不是浏览器,而是另一个遍历目录并将带有文件的http post请求发送到服务器的nod​​e.js脚本。 The request is created like this: 该请求是这样创建的:

fs.createReadStream(fileName).pipe(httprequest(options, function(error, response, body) { }));
function myRequest(request, response) {
  function writeFile(filePath, request, callback) {
    newFilePath = "/home/pi/upload"+filePath; //filePath looks like this: /home/blah/file.txt, the code below creates this structure under another directory, so newFilePath becomes /home/pi/upload/home/blah/file.txt
    tempFileName = path.basename(filePath)+".temp";
    console.log("Processing "+filePath+"->"+newFilePath+" with tempname " +tempFileName);
    var createFile = request.pipe(fs.createWriteStream(tempFileName));
    createFile.on("finish", function(error) { //Why does it fire the callback twice?
      if(error) {
        throw error;
      } else {
        moveFile(tempFileName, newFilePath, function(error) {
          if(error) {
            throw error;
          } else {
            console.log("OK");
          }
        });
      }
    });
  }

  function moveFile(tempFileName, newFilePath, callback) {
    dirPath = path.dirname(newFilePath);
    fs.stat(dirPath, function(error, stats) { //check if dir exists
      if(error == null) {
        console.log(dirPath+" already exists");
        fs.stat(tempFileName, function(error, stats) { //check if file exists
          if(error == null) {
            console.log("OK, writing "+newFilePath);
            fs.rename(tempFileName, newFilePath, function(error) {
              if(error) { //Error on the second run, because the file has been moved in the first run, shouldn't happen?
                throw error;
              } else {
                var myCB = JSON.stringify({fMove: "OK"});
                callback(myCB);
              }
            });
          } else {
            console.log("File exists");
          }
        });
      }
    });
  }
  writeFile(fileName, request, function() {
    //Do some stuff
  });
  request.on("end", function() {
    //Do other stuff
  }
});

http.createServer(myRequest).listen(8888);

Output from my script 我脚本的输出

Processing /home/pi/app/temp/client.js->/home/pi/upload/home/pi/app/temp/client.js with tempname client.js.temp
/home/pi/upload/home/pi/app/temp already exists
/home/pi/upload/home/pi/app/temp already exists
OK, Writing /home/pi/upload/home/pi/app/temp/client.js
OK, Writing /home/pi/upload/home/pi/app/temp/client.js

/home/pi/app/server.js:67
            throw error;
                  ^
{"fMove":"OK"}

Incorrect error handling made the script faulty. 错误的错误处理导致脚本错误。

In the moveFile function this part was wrong: 在moveFile函数中,这部分是错误的:

fs.rename(tempFileName, newFilePath, function(error) {
              if(error) {
                throw error;
              } else {
                var myCB = JSON.stringify({fMove: "OK"}); 
                callback(myCB); // <-- Malformatted callback! Should be callback(null, myCB);
              }

Which made this part of writeFile trigger on error and for some reason run twice: 这使writeFile的这一部分在错误时触发,并且由于某种原因运行两次:

moveFile(tempFileName, newFilePath, function(error) { //Should be moveFile(tempFileName, newFilePath, function(error, status) {
          if(error) {
            throw error;
          } else {
            console.log("OK");
          }
        });

When I fixed my code so it handles the error correctly, it works as intended! 当我修复代码以便正确处理错误时,它可以按预期工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM