我的脚本的这一部分试图生成一个将克隆硬盘驱动器的子进程。它基本上可以工作,但我遇到的问题是,当我遇到错误并想要存储输出时,它只存储输出的第一行,不包括我实际需要的东西。我已经在脚本之外运行了该命令,它给了我两行输出,第二行是失败时的错误。那么,我如何存储整个输出。非常感谢您的帮助,谢谢!
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
对象。
另请注意this warning :
Note: The
'exit'
event may or may not fire after an error has occurred. When listening to both the'exit'
and'error'
events, it is important to guard against accidentally invoking handler functions multiple times.
我可以看到一个可能的解决方案,如下所示:
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
。
关于javascript - Node 生成过程并存储输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45380143/