节点生成进程并存储输出



我的脚本的这一部分试图生成一个将要克隆硬盘驱动器的孩子。它基本上有效,但我遇到的问题是,当我遇到错误并想要存储输出时,它只存储输出的第一行,不包括我实际需要的东西。我已经在脚本外部运行了该命令,它给了我两行输出,第二行是失败时的错误。那么,我如何存储整个输出。非常感谢帮助,谢谢!

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

为了回答你的问题,我实际上无法对此进行测试,但我怀疑删除s.stderr.on('data', ...)处理程序将允许您确保err_msg是一个Error对象。

还要注意此警告:

注意:发生错误后,'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 + 'nn' + stacks.join('nn'))
}
success();
});
}

其中一个键是使用error.stack属性,因为默认情况下,当强制转换为字符串时,错误通常倾向于记录message属性。此属性可能是您在代码中获得的单行反馈,因为您从未检查过err_msg.stack

最新更新