1
다음 코드에서 createFile 콜백이 두 번 발생하는 이유는 무엇입니까? 이는 서버 (아래)가 동시에 두 개 이상의 요청을 처리 할 때만 발생하며 한 번만 요청한 경우에는 발생하지 않습니다. 게시물의 하단에 출력. 요청을하는 클라이언트는 브라우저가 아니며 다른 node.js 스크립트가 디렉토리를 반복하고 서버에 파일과 함께 http 게시 요청을 보냅니다. 요청은 다음과 같이 작성됩니다Node.js가 콜백을 두 번 발생시키는 이유는 무엇입니까?
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);
출력 잘못된 오류 처리 스크립트에 오류가 만든
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"}
'var'변수 앞에 접두사를 두지 않으므로 전역 변수가되어 각 호출에서 덮어 쓰게됩니다. – robertklep
제안에 감사드립니다. 변수를 덮어 쓰지 않도록 코드를 변경했지만 불행히도 결과가 변경되지 않았습니다. – sacredheart
편집하는 대신에 당신은 자신의 질문에 대한 답을 써야합니다. 그러나 오래 기다리면 자신의 대답을 받아들이기를 기다리게됩니다. 다른 사람이 더 나은 대답을 쓰지 않으면 올바른 것으로 표시하십시오. 앞으로 Google을 사용하는 사람들에게 많은 도움이됩니다. – Chev