【问题标题】:How to parse output of stdout如何解析标准输出的输出
【发布时间】:2017-11-12 05:09:13
【问题描述】:

例如,如果在 nodejs 子进程中执行类似:

exec("find /path/to/directory/ -name '*.txt'", callback);

如何将回调函数中的流输出解析为数组以获得类似的结果?

['file-1.txt', 'file-2.txt', 'file-3.txt', ...]

当前输出如下:

path/to/file-1.txt
path/to/file-2.txt
path/to/file-3.txt

感谢您的帮助

【问题讨论】:

  • 这里回调返回什么参数??
  • function callback(error, stdout, stderr) { ... } 返回的输出如下:path/to/file1.txtpath/to/file1.txt
  • 回调的返回输出如下:path/to/file1.txt
    path/to/file2.txt
    path/to/file3.txt
  • 这可能对你有帮助-- stackoverflow.com/questions/33196261/…

标签: arrays node.js exec stdout child-process


【解决方案1】:
const exec = require('child_process').exec;
exec("find /path/to/directory -name '*.txt'", (error, stdout, stderr) => {
    if (error) {
        // handle error
    } else {
        var fileNames = stdout.split('\n').filter(String).map((path) => {
            return path.substr(path.lastIndexOf("/")+1);
        });
        console.log(fileNames); // [ 'file1.txt', 'file2.txt', 'file3.txt' ]
    }
});

const exec = require('child_process').exec;
exec("ls /path/to/directory | grep .txt", (error, stdout, stderr) => {
    if (error) {
        // handle error
    } else {
        var fileNames = stdout.split(/[\r\n|\n|\r]/).filter(String);
        console.log(fileNames); // [ 'file1.txt', 'file2.txt', 'file3.txt' ]
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    相关资源
    最近更新 更多