exec.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env node
  2. /*
  3. Licensed to the Apache Software Foundation (ASF) under one
  4. or more contributor license agreements. See the NOTICE file
  5. distributed with this work for additional information
  6. regarding copyright ownership. The ASF licenses this file
  7. to you under the Apache License, Version 2.0 (the
  8. "License"); you may not use this file except in compliance
  9. with the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing,
  12. software distributed under the License is distributed on an
  13. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. KIND, either express or implied. See the License for the
  15. specific language governing permissions and limitations
  16. under the License.
  17. */
  18. var child_process = require("child_process");
  19. var Q = require("q");
  20. // constants
  21. var DEFAULT_MAX_BUFFER = 1024000;
  22. // Takes a command and optional current working directory.
  23. // Returns a promise that either resolves with the stdout, or
  24. // rejects with an error message and the stderr.
  25. //
  26. // WARNING:
  27. // opt_cwd is an artifact of an old design, and must
  28. // be removed in the future; the correct solution is
  29. // to pass the options object the same way that
  30. // child_process.exec expects
  31. //
  32. // NOTE:
  33. // exec documented here - https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
  34. module.exports = function(cmd, opt_cwd, options) {
  35. var d = Q.defer();
  36. if (typeof options === "undefined") {
  37. options = {};
  38. }
  39. // override cwd to preserve old opt_cwd behavior
  40. options.cwd = opt_cwd;
  41. // set maxBuffer
  42. if (typeof options.maxBuffer === "undefined") {
  43. options.maxBuffer = DEFAULT_MAX_BUFFER;
  44. }
  45. try {
  46. child_process.exec(cmd, options, function(err, stdout, stderr) {
  47. if (err) d.reject("Error executing \"" + cmd + "\": " + stderr);
  48. else d.resolve(stdout);
  49. });
  50. } catch(e) {
  51. console.error("error caught: " + e);
  52. d.reject(e);
  53. }
  54. return d.promise;
  55. };