iT邦幫忙

0

請教 res.end置放位置

如題
目前有兩種指令,一種為長指令
127.0.0.1:1337/FirstPassYield?filePath=D:\Project\SmartFactory\EXE

一種為短指令:
127.0.0.1:1337/MachineTemperature
我再程式碼裡用 if(feeback.search) 區隔開,短指令跑短指令區,長指令跑長指令區
分為兩個fuction,並在if(feeback.search)末段放進res.end();
等於這兩個fuction最後都只有一個end結尾,現在在長指令及短指令的fuction理個多加了尋找檔案的功能,當我尋找完檔案後顯示給命令提示字源以及瀏覽器顯示,code為

  if(FilePath_ay[0]==="SmartFactoryFile")
  {      
    var i1000JsonFile_A=FilePath_ay[1]+".json";                  // i1000JsonFile_A = 檔名+副檔名
    console.log("i1000JsonFile_A = "+i1000JsonFile_A);
    RootPath_A=RootPath_A+FilePath_ay[1]+".json";                // 總路徑
    var fs = require('fs')
    fs.stat(RootPath_A, function(err, stat)                      // 
    {
      if(stat&&stat.isFile()) 
      {
        fs.readFile(RootPath_A, function (err, data)
        {
          console.log(data.toString());
          res.write(data);
        });
      }  
      else 
      {
        console.log("400 Bad Request. The < "+i1000JsonFile_A+" > not found.");
        res.write("400 Bad Request. The < "+i1000JsonFile_A+" > not found.");
      }

----------------------------------------------------------------------------- 在readFile裡面只要沒有res.end();,就不會將顯示結果顯示於瀏覽器上,並且網頁也會無回應,但加了end又會與function抵觸,錯誤碼為
Error:write after end 請問我應該怎麼作,能讓找完檔案後的資料顯示於瀏覽器上,又不會有錯誤,請高手教導我,謝謝您

看更多先前的討論...收起先前的討論...
froce iT邦大師 3 級 ‧ 2018-09-11 20:16:15 檢舉
放全部的code吧,感覺問題不在這段上。
dance0000 iT邦新手 5 級 ‧ 2018-09-12 09:49:50 檢舉
// NodecatchURL.js------->>version 2.0.0
// GET /api/messages
var http = require('http'); // 載入 Node.js 原生模組 http
var url = require('url'); // 載入 Url模組
var RawArray = ["filePath","parentPanelSerialNumber","dutSerialNumber"];// 參數陣列
var FirstWord_ay=["FirstPassYield","DutDetailedTestResults","WorstProbeReport"]; // 指令陣列
var Shortcommad_ay =["Status","MachineTemperature","MachineConfiguration","DiagnosticTestResults","SmartFactoryStatus","File","SmartFactoryFile"];
var ShortcommadForI1000_Ar = []; // 短指令for 1000 長指令陣列
var LongcommadForSocket_Ar = []; // 長指令for shopfloor
var I1000root = 'C:\\Agilent_i1000\\script\\REST_API\\';
var SmartFactoryroot = 'C:\\Agilent_i1000\\script\\SmartFactoryREST_API\\';
var RootPath_A="C:\\Agilent_i1000\\Report\\MQTT log\\";
var i1000FilePath=" ";
var SmartFactoryFilePath=" ";
var LongString_S = "";
var FilePath_S="" ; // 根目錄
var Num_S="";
var DirPath_Ay; // 路徑分離
var Caseflag=false;
var FileFalg=false;
var dutSerialNumber_flag=true;
var CaseCount_Ar;
var Otherflag = false;
var OutSearchFirstwordflag = false;
var OutSearchWattingflag = false;
var FirstWordFailFlag = false;
var InSearchFirstFlag = false;
var QuestionMarkLastOneMarkflag = false;
var QuestionMarkLastTwoMarkflag = false;
var UnFind_fg=false;
var status ='status.txt'
var Ready ='Ready.txt'
var fs = require('fs');
http.createServer(function (req, res)
{
var feeback = url.parse(req.url, true);
if(req.url!=="/favicon.ico")
{
if(feeback.search)
{
LongString_S="";
var FirstString_Ar=feeback.pathname.split("/"); // Pathname 為第一到指令 [0]=null [1]=第一道指令
InSearchFirstFlag=false;
for(var a = 0 ; a <= FirstWord_ay.length;a++) // 長指令裡的短指令符合 三道短指令
{
if(FirstString_Ar[1]===FirstWord_ay[a]) // 擷取指令 有符合三道短指令其中一道進入
{
LongString_S=LongString_S+FirstString_Ar[1]; // 長指令里第一筆資料相符
if(LongString_S==="FirstPassYield") // 定義進入位置區
Num_S=1;
if(LongString_S==="DutDetailedTestResults")
Num_S=2;
if(LongString_S==="WorstProbeReport")
Num_S=3;
InSearchFirstFlag=true;
switch(Num_S)
{
case 1:
CaseCount_Ar=feeback.search.split("?"); // FPY fliepath存在則進入
if(CaseCount_Ar.length===2)
Caseflag=true;
break
case 2:
CaseCount_Ar=feeback.search.split("?"); // DUT test result fliepath 存在 旗標打開
Caseflag=true;
console.log("Caseflag"+Caseflag)
if(CaseCount_Ar.length===2)
{
CaseCount_Ar=feeback.search.split("&"); // dutSerialNumber 存在 旗標打開
if(CaseCount_Ar.length!==2)
Caseflag=false;
}
break
case 3:
CaseCount_Ar=feeback.search.split("?"); // Wost
if(CaseCount_Ar.length===2)
Caseflag=true;
break
}
break;
}
}
if(!InSearchFirstFlag) // 旗標若未開啟代表失敗 指令錯誤或判斷不到指令
{
res.write(' 400- <'+FirstString_Ar[1]+'> error.');
console.log(' 400- <'+FirstString_Ar[1]+'> error.');
}
if(!Caseflag && InSearchFirstFlag)
{
if(Num_S===1||Num_S===3)
{
res.write(' 400- < filePath > is not found');
console.log(" 400- < filePath > is not found");
}
if(Num_S===2)
{
res.write(' 400- < filePath or dutSerialNumber > is not found');
console.log(" 400- < filePath or dutSerialNumber > is not found");
}
} //*/
if(Caseflag && InSearchFirstFlag) // 長指令裡短指令符合才進入
{
Caseflag=false;
dutSerialNumber_flag=true;
InSearchFirstFlag = false ;
var AllURL_S = feeback.search;
var split_Ar= AllURL_S.split("&");
for(var b = 0 ; b < split_Ar.length ; b++ )
{
for(var c = 0 ; c <= RawArray.length ; c++ )
{
if(b===0)
{
var HandleQuestionMark_S=split_Ar[0]; // 未去掉開頭 指令問號以後
var Done_S=HandleQuestionMark_S.substr(1,split_Ar[0].length); // 去掉開頭 同指令去掉問號
if(Done_S.indexOf(RawArray[c])!=-1)
{
QuestionMarkLastOneMarkflag=true;
LongString_S=LongString_S+"&"+Done_S; // LongString_S=LongString_S+"\\"+Done_S;
break;
}
}
if(b > 0)
{
var string_S = split_Ar[b];
if(string_S.indexOf(RawArray[c] )!=-1)
{
LongString_S=LongString_S+"&"+string_S; // LongString_S=LongString_S+"/"+string_S;
QuestionMarkLastTwoMarkflag = true;
break;
}
}
} //*/
while(LongString_S.indexOf("%20") >= 0) // 把所有空白所顯示的%20改成" "
{
LongString_S=LongString_S.replace("%20"," ");
var ss=LongString_S.indexOf("%20");
}//*/
if( b===0 && !QuestionMarkLastOneMarkflag)
{ // 第一步驟沒過則進入
var Done_Ar=Done_S.split("=");
console.log(" 400 Bad Request. <"+Done_Ar[0]+"> error.");
res.write(" 400 Bad Request. <"+Done_Ar[0]+"> error.");
break;
}
if( b>0 && QuestionMarkLastOneMarkflag && !QuestionMarkLastTwoMarkflag)
{ // 第一步驟沒過則進入
var string_Ar=string_S.split("=");
console.log(" 400 Bad Request. <"+string_Ar[0]+"> error.");
res.write(" 400 Bad Request. <"+string_Ar[0]+"> error.");
break;
}

if(QuestionMarkLastTwoMarkflag)
{
if( b > 0 && b!==(split_Ar.length)-1 )
{ // 第一筆跑完旗標還沒開啟 OK
QuestionMarkLastTwoMarkflag = false;
}
if( b > 0 && b===(split_Ar.length)-1)
{ // 最長二筆全測完 且都正確
DirPath_Ay=LongString_S.split("=");
DirPath_Ay=DirPath_Ay[1].split("&");
var fs = require('fs')
fs.stat(DirPath_Ay[0], function(err, stat) // DUT OK
{
if(stat&&stat.isFile())
{
console.log("File is exists.");
fs.readFile(DirPath_Ay[0], function (err, data)
{
LongcommadForSocket_Ar.push(LongString_S);
console.log("LongcommadForSocket_Ar[0] ="+LongcommadForSocket_Ar[0]);
// res.write(data);
// res.end();
});
}
else
{
console.log("400 Bad Request. The < "+DirPath_Ay[0]+" > not found.");
res.write("400 Bad Request. The < "+DirPath_Ay[0]+" > not found.");
res.end();
}
})
} //*/
}
if( b === (split_Ar.length)-1 && (split_Ar.length) === 1 && QuestionMarkLastOneMarkflag) // 僅有 FilePath測完
{
var fs = require('fs');
console.log("LongString_S = "+LongString_S);
DirPath_Ay=LongString_S.split("=");
fs.readdir(DirPath_Ay[1], (err, files)=>
{
if(Num_S===1)
{
for (f of files)
{
if (f.endsWith(".fpy"))
{
LongcommadForSocket_Ar.push(LongString_S);
console.log("LongString_S ="+LongString_S);
console.log("GOOD FPY");
FileFalg=true;
}
}
if(!FileFalg)
{
console.log("cant not found any .fpy");
}
}
if(Num_S===3)
{
for (f of files)
{
if (f.endsWith(".wpr")) // 尋找此副檔名檔案有無存在此路徑
{
LongcommadForSocket_Ar.push(LongString_S);
console.log("LongString_S ="+LongString_S);
console.log("GOOD wpr");
FileFalg=true;
}
}
if(!FileFalg)
{
console.log("cant not found any .wpr");
}
}
});
FileFalg=false;
}
}
QuestionMarkLastOneMarkflag=false;
QuestionMarkLastTwoMarkflag=false;
}
res.end();
}
//
else
{
var FirstString_Ar=feeback.pathname.split("/"); // 沒有第二筆資料進入
var Catch=FirstString_Ar[1].substring(0,1);
FirstString_Ar[1]=FirstString_Ar[1].substring(1,FirstString_Ar[1].length);
Catch=Catch.toUpperCase();
FirstString_Ar[1]=Catch+FirstString_Ar[1];
console.log("FirstString_Ar[0] = "+FirstString_Ar[0]);
console.log("FirstString_Ar[1] = "+FirstString_Ar[1]);
if(FirstString_Ar[1]!=='Status' && FirstString_Ar[1] !=="SmartFactoryStatus" )
{
for(var a = 0 ; a <= Shortcommad_ay.length;a++) // 比對第一筆資料 FirstString_Ar為""/"返回的資料陣列(第一筆)
{
if(!FirstString_Ar[1]) // 資料為空
{
OutSearchWattingflag = true;
// res.end();
break;
}
else
{
if(FirstString_Ar[1]===Shortcommad_ay[a] ) // 第一筆資料 短指令 相符push Firstdataflag
{
ShortcommadForI1000_Ar.push(FirstString_Ar[1]);
res.write('200-OK');
console.log("200-OK");
OutSearchFirstwordflag = true;
break;
}
}
}
if(!OutSearchWattingflag) // 如果第一筆資料不合
{
if(!OutSearchFirstwordflag && FirstString_Ar[1] !== "SmartFactoryStatus" && FirstString_Ar[1].indexOf("File")===-1 && FirstString_Ar[1].indexOf("SmartFactoryFile")===-1)
{
res.write('400-bad Request'); // 短指令錯誤
console.log("400-bad Request");
}
}
OutSearchWattingflag = false;
OutSearchFirstwordflag = false;
}
if(FirstString_Ar[1]==='Status' )
{
UnFind_fg=false;
if(ShortcommadForI1000_Ar.length > 0)
{
ShortcommadForI1000_Ar.reverse();
Pop=ShortcommadForI1000_Ar.pop();
res.write('i1000:'+" "+Pop+" "+"\r\n"+" ");
console.log('i1000:'+" "+Pop+" "+"\r\n"+" ");
ShortcommadForI1000_Ar.reverse();
}
}
if(FirstString_Ar[1]==='SmartFactoryStatus')
{
if(LongcommadForSocket_Ar.length > 0)
{
LongcommadForSocket_Ar.reverse();
LongcommadPop=LongcommadForSocket_Ar.pop();
res.write('SmartFactory:'+" "+LongcommadPop+"\r\n");
console.log('SmartFactory:'+" "+LongcommadPop+"\r\n");
res.write("\r\n");
console.log("\r\n");
LongcommadForSocket_Ar.reverse();
}
}
var FilePath_ay=FirstString_Ar[1].split("=");
if(FilePath_ay[0]==="File")
{
console.log()
var i1000JsonFile_A=FilePath_ay[1]; // i1000JsonFile_A = 檔名+副檔名
RootPath_A=RootPath_A+FilePath_ay[1]; // 總路徑
var fs = require('fs')
fs.stat(RootPath_A, function(err, stat) //
{
if(stat&&stat.isFile())
{
fs.readFile(RootPath_A, function (err, data)
{
console.log(data.toString());
res.write(data);
res.end();
});
}
else
{
console.log("400 Bad Request. The < "+i1000JsonFile_A+" > not found.");
res.write("400 Bad Request. The < "+i1000JsonFile_A+" > not found.");
res.end();
}
}) //*/
}
if(FilePath_ay[0]==="SmartFactoryFile")
{
var i1000JsonFile_A=FilePath_ay[1]+".json"; // i1000JsonFile_A = 檔名+副檔名
console.log("i1000JsonFile_A = "+i1000JsonFile_A);
RootPath_A=RootPath_A+FilePath_ay[1]+".json"; // 總路徑
var fs = require('fs')
fs.stat(RootPath_A, function(err, stat) //
{
if(stat&&stat.isFile())
{
fs.readFile(RootPath_A, function (err, data)
{
console.log(data.toString());
res.write(data);
});
}
else
{
console.log("400 Bad Request. The < "+i1000JsonFile_A+" > not found.");
res.write("400 Bad Request. The < "+i1000JsonFile_A+" > not found.");
}
}) //*/
}
res.end();
}
}
}).listen(1337);
console.log('========================Serever is running Ver:2.0.0============================');//*/
麻煩您了
dance0000 iT邦新手 5 級 ‧ 2018-09-12 09:58:01 檢舉
還是F前輩可以給我您的Mail,我把code寄給您,因為這樣沒排版您也不好Debug
froce iT邦大師 3 級 ‧ 2018-09-13 09:38:03 檢舉
用訊息丟連結給我,幫你看看。

尚未有邦友回答

立即登入回答