var promise = require('child-process-promise').spawn; promise('some_command_producing_output') .then(function (result) { ... }) .catch(function (err) { ... });
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:
RunCommandAndProcess('some_command_producing_output') .then(function (result) { ... }) .catch(function (err) { ... });
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
const spawn = require('child_process').spawn; const spawnPromise = (cmd, args) => { return new Promise((resolve, reject) => { try { const runCommand = spawn(cmd, args); runCommand.stdout.on('data', data => resolve(data.toString())); runCommand.on('error', err => { throw new Error(err.message); }); } catch (e) { reject(e); } }); };
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:
spawnPromise('ls', ['-la']).then(data => console.log('data: ', data));
Or
const result = await spawnPromise('ls', ['-la']);