JavaScript
x
10
10
1
var promise = require('child-process-promise').spawn;
2
3
promise('some_command_producing_output')
4
.then(function (result) {
5
6
})
7
.catch(function (err) {
8
9
});
10
What I want is to add some processing after command produced output in stdout. So finally I want to create a function to use like this:
JavaScript
1
8
1
RunCommandAndProcess('some_command_producing_output')
2
.then(function (result) {
3
4
})
5
.catch(function (err) {
6
7
});
8
The function should use promise from child-process-promise, wait until successful result produced and return promise for processing data.
Advertisement
Answer
Welcome to Stack Overflow @ScHoolboy.
I cansuggest you use a basic child-process module from Node.js and promising it yourself in the following way
JavaScript
1
16
16
1
const spawn = require('child_process').spawn;
2
3
const spawnPromise = (cmd, args) => {
4
return new Promise((resolve, reject) => {
5
try {
6
const runCommand = spawn(cmd, args);
7
runCommand.stdout.on('data', data => resolve(data.toString()));
8
runCommand.on('error', err => {
9
throw new Error(err.message);
10
});
11
} catch (e) {
12
reject(e);
13
}
14
});
15
};
16
Where:
- cmd – command, for example, “echo”
- args: array of arguments, for example [“Hello world”]
You can call the function as RunCommandAndProcess if you need 🙂
Example of usage:
JavaScript
1
2
1
spawnPromise('ls', ['-la']).then(data => console.log('data: ', data));
2
Or
JavaScript
1
2
1
const result = await spawnPromise('ls', ['-la']);
2