0

For example if execute in nodejs child process something like:

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

How can i parse the streamed output in my callback function to an array to get something like so?

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

The current output is like following:

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

Thanks for helping

4
  • what parameters does callback returns here?? Commented Nov 11, 2017 at 15:49
  • function callback(error, stdout, stderr) { ... } The returned output looks like so: path/to/file1.txt path/to/file1.txt Commented Nov 11, 2017 at 15:52
  • The returned output of the callback looks like so: path/to/file1.txt <br/> path/to/file2.txt <br/> path/to/file3.txt Commented Nov 11, 2017 at 15:59
  • This might help you-- stackoverflow.com/questions/33196261/… Commented Nov 11, 2017 at 16:03

1 Answer 1

2
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' ]
    }
});

or

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' ]
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.