2017-07-28 56 views
1

我的腳本的這一部分正在嘗試產生一個將克隆硬盤驅動器的孩子。它基本上可行,但我遇到的問題是當我遇到錯誤並想要存儲輸出時,它只存儲輸出的第一行,排除我實際需要的東西。我在腳本之外運行命令,它給了我兩行輸出,第二行是失敗的錯誤。所以,我怎麼能存儲整個輸出。非常感謝幫助,謝謝!節點產卵過程和存儲輸出

NtfsPartition.prototype.WriteFs = function(filename, progress, success, error) { 
    console.log('Writing NTFS FS'); 
    var s = spawn("ntfsclone", ['--restore-image', '--overwrite', this.dev, filename]); 
    var err_msg = ''; 
    s.on('error', function(err) { 
     err_msg = err; 
    }); 
    s.stderr.on('data', function(data) { 
     err_msg += data.toString(); 
    }); 
    s.stdout.on('data', function(data) { 
     var match = data.toString().match(kNtfsWriteFsProgressRegex); 
     if(!match) { 
      return; 
     } 
     progress(match[1]); 
    }); 
    s.on('exit', function(code) { 
     if(code != 0) { 
      console.log(err_msg); 
      return error('Error: ' + code + ' - ' + err_msg); 
     } 
     success(); 
    }); 
} 
+0

歡迎來到Stack Overflow!這是一個很好的第一個問題,我們期待着您對社區的進一步貢獻。我只是添加了一些標籤以使您的問題更容易找到,並且爲了將來參考,您可以使用4個空格縮進大塊代碼,而不是使用內聯反引號。雖然這些都是非常小的細節,並且我確信快速訪問[幫助]會教你一些其他好的提示。 –

回答

0

要回答你的問題,我無法實際測試,但我懷疑,去除s.stderr.on('data', ...)處理程序將允許您以確保err_msgError對象。

還注意到this warning

:該'exit'事件可能發生了錯誤之後,或者可能不會觸發。在收聽'exit''error'事件時,防止意外地多次調用處理函數是很重要的。

我看到一個可能的解決方案看起來像這樣:

NtfsPartition.prototype.WriteFs = function(filename, progress, success, error) { 
    console.log('Writing NTFS FS'); 
    var s = spawn("ntfsclone", ['--restore-image', '--overwrite', this.dev, filename]); 
    var errors = []; 
    // if possible, might get multiple of these 
    // if not, this still works for a single error 
    s.on('error', function(err) { 
     errors.push(err) 
    }); 
    s.stdout.on('data', function(data) { 
     var match = data.toString().match(kNtfsWriteFsProgressRegex); 
     if(!match) { 
      return; 
     } 
     progress(match[1]); 
    }); 
    // guaranteed to be called, whereas 'exit' is not(?) 
    s.on('close', function(code) { 
     if(code != 0) { 
      var stacks = errors.map(function (err) { 
       return err.stack; 
      }); 
      // all the errors 
      return error('Error: ' + code + '\n\n' + stacks.join('\n\n')) 
     } 
     success(); 
    }); 
} 

的關鍵之一是使用error.stack屬性,因爲錯誤的人通常不是在默認情況下登錄的message屬性,當裹挾一個字符串。此屬性可能是您在代碼中獲得的單行反饋,因爲您從未檢查過err_msg.stack

+1

嗨,去除s.stderr.on訣竅!感謝您的幫助,非常感謝 – Ian

+0

沒問題,很高興我能幫上忙 –