sexec.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. var path = require('path');
  2. var fs = require('fs');
  3. var child = require('child_process');
  4. var DEFAULT_MAXBUFFER_SIZE = 20 * 1024 * 1024;
  5. function _exec(command, options, callback) {
  6. options = options || {};
  7. if (typeof options === 'function') {
  8. callback = options;
  9. }
  10. if (typeof options === 'object' && typeof callback === 'function') {
  11. options.async = true;
  12. }
  13. if (!command) {
  14. try {
  15. console.error('[sexec] must specify command');
  16. } catch (e) {
  17. return;
  18. }
  19. }
  20. options = Object.assign({
  21. silent: false,
  22. cwd: path.resolve(process.cwd()).toString(),
  23. env: process.env,
  24. maxBuffer: DEFAULT_MAXBUFFER_SIZE,
  25. encoding: 'utf8',
  26. }, options);
  27. var c = child.exec(command, options, function (err, stdout, stderr) {
  28. if (callback) {
  29. if (!err) {
  30. callback(0, stdout, stderr);
  31. } else if (err.code === undefined) {
  32. // See issue #536
  33. /* istanbul ignore next */
  34. callback(1, stdout, stderr);
  35. } else {
  36. callback(err.code, stdout, stderr);
  37. }
  38. }
  39. });
  40. if (!options.silent) {
  41. c.stdout.pipe(process.stdout);
  42. c.stderr.pipe(process.stderr);
  43. }
  44. }
  45. module.exports = _exec;