2014-03-28 15 views
0

此代碼基於Javascript的專業Node.js的構建可擴展的軟件數據發出:Node.js的代碼排序 - 這可能是之前監聽到位

var spawn = require('child_process').spawn; 

// Spawn the child with a node process executing the plus_one app 
var child = spawn('node', ['06_plus_one.js']); 

// Call this function every 1 second (1000 milliseconds): 
setInterval(function() { 

    // Create a random number smaller than 10.000 
    var number = Math.floor(Math.random() * 10000); 

    // Send that number to the child process: 
    child.stdin.write(number + "\n"); 

    // Get the response from the child process and print it: 
    child.stdout.on('data', function(data) { 
    console.log('child replied to ' + number + ' with: ' + data); 
    }); 
}, 1000); 

child.stderr.on('data', function(data) { 
    process.stdout.write(data); 
}); 

子進程簡單的增加從父母傳過來的號碼。 child.stdin.write()是否有可能進入子進程,並且在父代註冊其data偵聽器之前,孩子已經發出了data事件?

還有第二個問題。該代碼最初有不正確的子程序文件名並引發錯誤。我如何從產卵中捕獲錯誤?

+1

通過在父文件的起始處調用'fs.readFile'或'fs.readFileSync'來測試子腳本的存在性,並且查找沒有錯誤和非零長度。這不會告訴你,如果子腳本是有效的,但會盡快識別缺少的腳本。 – Paul

回答

2
  • 警告,檢測到內存泄漏!不要在循環中附加一個監聽器(setInterval)。你每秒鐘都在添加一個監聽器。將這個代碼的setInterval回調外:

    child.stdout.on('data', function(data) { 
        console.log('child replied to ' + number + ' with: ' + data); 
    }); 
    

  • 子進程簡單的增加從父傳遞的數量。是否有可能child.stdin.write()進入子進程,並在父註冊其數據偵聽器之前,該子進程已經發出數據事件?

    號兩個原因:

    • 閱讀以前的評論。你必須在setInterval()之外附加監聽器,就像stderr.on("data")一樣。
    • 孩子會在稍後打勾時發送消息。在當前循環中,您可以編寫消息,並且在將來的時間刻度中,您會收到孩子的回覆。這是1個線程(在javascript層)的異步定義。

  • 另外第二個問題。該代碼最初有不正確的子程序文件名並引發錯誤。我如何從產卵中捕獲錯誤?

    你試過嘗試捕捉spawn()函數嗎?

+0

我試過{catch(err){},它似乎沒有抓住它。 – huggie

0

子進程只增加從父進程傳遞的數字。 有沒有可能child.stdin.write()進入子進程和 之前父註冊其數據偵聽器,孩子已經發出 數據事件?

因爲stream.write操作是trrenly async,NO。

+0

感謝您的解釋。但是爲什麼對於streamwriter我注意到,如果我做'outstream.end()'然後'outstream.write()',如果我沒有代碼捕獲錯誤('outstream.on('error',function (err){})')已經運行,它會拋出沒有錯誤處理程序,儘管是異步? – huggie