节点生成进程和存储输出

时间:2017-07-28 18:27:20

标签: javascript node.js error-handling ntfs spawn

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

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

1 个答案:

答案 0 :(得分: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

相关问题