节点产生进程和存储输出

我的脚本的这一部分正试图产生一个克隆硬盘驱动器的孩子。 它基本上工作,但我遇到的问题是,当我遇到一个错误,并希望存储输出,它只存储输出的第一行,排除我实际需要的东西。 我已经在脚本之外运行了这个命令,它给了我两行输出,如果失败,第二行是错误。 那么,我怎么能存储整个输出。 非常感谢帮助,谢谢!

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(); }); } 

要回答你的问题,我实际上不能testing这个,但我怀疑删除s.stderr.on('data', ...)处理程序将允许你确保err_msg是一个Error对象。

还要注意这个警告 :

注意 :发生错误后, 'exit'事件可能会或可能不会触发。 在收听'exit''error'事件时,防止意外地多次调用处理函数是很重要的。

我可以看到一个可能的解决scheme如下所示:

 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属性,因为错误通常倾向于loggingmessage属性,而不是默认情况下强制为string。 此属性可能是您在代码中获得的单行反馈,因为您从未检查过err_msg.stack