javascript NodeJS读取并解析每一行stdout

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12955154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:30:39  来源:igfitidea点击:

NodeJS read and parse each line of stdout

javascriptnode.js

提问by Programmer

I have a NodeJS script that 'exec's a child process to capture cat dump of a file:

我有一个 NodeJS 脚本,它是一个子进程来捕获文件的 cat 转储:

var exec = require('child_process').exec;
var result = '';
var child = exec('./scripts/first.sh',function(err, stdout, stderr) {
    result = stdout.split("=");
});

If in case the file is not there I would take dump of a different file:

如果文件不存在,我会转储不同的文件:

var result = '';
var child = exec('./scripts/first.sh',function(err, stdout, stderr) {
    result = stdout.split("=");
    if(stdout.indexOf('No such file or directory') != -1){
        var child = exec('./scripts/second.sh', function(err, stdout, stderr) {
            result = stdout.split("=");
    });
});

Finally I log the value of result variable:

最后我记录结果变量的值:

console.log(result);

The files would have data like mentioned below:

这些文件将包含如下所述的数据:

line_1 = 7888
line_2 = 8998
line_3 = 9090
line_4 = 9097

I need to parse and extract values of line_1 and line_3?

我需要解析和提取 line_1 和 line_3 的值吗?

The result variable does not shows any value. My idea was to get the stdout data in a string variable and use some search mechanism.

结果变量不显示任何值。我的想法是在字符串变量中获取标准输出数据并使用一些搜索机制。

Though I am not sure of the approach as I am not much experience on JS / NodeJS.

虽然我不确定这种方法,因为我对 JS / NodeJS 没有太多经验。

==EDIT==

==编辑==

Please find a replica of the function I have written.

请找到我编写的函数的副本。

var exec = require('child_process').exec;

function getdetail() {
        var result = '';
        var child = exec('./scripts/first.sh', function(err, stdout, stderr) {
                if(stdout.indexOf('No such file or directory') != -1){
                        var child = exec('./scripts/second.sh',function(err, stdout, stderr) {
                        result = stdout.toString().split("=");
                        console.log(result);
                        });
                }
                else
                {
                        result = stdout.toString().split("=");
                        console.log(result);
                }
        });
}

The tostring() on stdout stream object did the trick but I get console logs as mentioned below:

stdout 流对象上的 tostring() 做到了这一点,但我得到了如下所述的控制台日志:

[ 'spawn ssh -o UserKnownHostsFile',
  '/dev/null -o StrictHostKeyChecking',
  'no [email protected] cat ver.txt\r\nWarning: Permanently added \'www.mybox.com,XX.XX.XX.XX\' (RSA) to the list of known hosts.\r\r\[email protected]\'s password: \r\line_1',
  '9400\r\nline_2',
  '3508\r\nline_3',
  '77f3\r\nline_4',
  '/tmp\r\nline_5',
  '/tmp/ramdisk/\r\nline_5',
  '77f3\r\n' ]

How can I extract value of line_1 and line_3?

如何提取 line_1 和 line_3 的值?

回答by jsalonen

execis asynchronous.Thus, if you write something like:

exec是异步的。因此,如果你写这样的东西:

var result = '';
var child = exec('...'), function() { result = 'abc'; } );
console.log(result);

Then resultmaybe be empty, since console.log(result)can and often will get executed before exec returns to its callback and fill in the new value.

然后result可能是空的,因为console.log(result)可以并且经常会在 exec 返回其回调并填充新值之前执行。

To fix this, you need to process the result asynchronously in the exec's callback function.

要解决此问题,您需要在 exec 的回调函数中异步处理结果。

Also I'm not sure if the way you check for errors is the best possible. Instead of checking for "no such file or directory", you could simply test if errhas non-null value:

另外,我不确定您检查错误的方式是否最好。您可以简单地测试是否err具有非空值,而不是检查“没有这样的文件或目录” :

if(err) {

Putting this all together we end up with the following code:

将所有这些放在一起,我们最终得到以下代码:

var exec = require('child_process').exec;

var result = '';
var processResult = function(stdout) {
    var result = stdout.split("=");
    console.log(result);
};

var child = exec('./scripts/first.sh',function(err, stdout, stderr) {
    if(err) {
        var child = exec('./scripts/second.sh', function(err, stdout, stderr) {                         
            processResult(stdout);
        });
    } else {            
        processResult(stdout);
    }
});

If you need to further process the stdout data, you need to iterate through it to find out all possible occurences of strings containing "key=value". Here is a rough idea:

如果需要进一步处理 stdout 数据,则需要遍历它以找出所有可能出现的包含“key=value”的字符串。这是一个粗略的想法:

var processResult = function(stdout) {  
    var lines = stdout.toString().split('\n');
    var results = new Array();
    lines.forEach(function(line) {
        var parts = line.split('=');
        results[parts[0]] = parts[1];
    });

    console.log(results);
};

I hope this gets you started.

我希望这能让你开始。