Created
May 30, 2017 16:17
-
-
Save ThomasG77/6037abbd364d4bf1285da8d8a1c0f3cb to your computer and use it in GitHub Desktop.
Promise and exec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// Idea mainly borrowed from https://stackoverflow.com/a/30883005 | |
const Promise = require('bluebird'); // Not required if you prefer using native promise | |
const exec = require('child_process').exec; | |
function promiseExec(command) { | |
var child = exec(command); | |
return new Promise(function (resolve, reject) { | |
child.addListener("error", reject); | |
child.stderr.on('data', function (data) { | |
reject(data); | |
}); | |
child.stdout.on('data', function (data) { | |
resolve(data); | |
}); | |
}); | |
} | |
promiseExec('wc -l my_file.sql').then(function (results) { | |
console.log(results.replace(/[\n\n]/g, '').split(' ')[0]); | |
}, function (err) { | |
console.log('Promise rejected: ' + err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment