版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

async.js 2.5 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. "use strict";
  2. const normalizeArgs = require("./normalize-args");
  3. const normalizeResult = require("./normalize-result");
  4. const maybe = require("call-me-maybe");
  5. const spawn = require("cross-spawn");
  6. module.exports = async;
  7. /**
  8. * Executes the given command asynchronously, and returns the buffered
  9. * results via a callback or Promise.
  10. *
  11. * @param {string|string[]} command - The command to run
  12. * @param {string|string[]} [args] - The command arguments
  13. * @param {object} [options] - options
  14. * @param {function} [callback] - callback that will receive the results
  15. *
  16. * @returns {Promise<Process>|undefined}
  17. * Returns a Promise if no callback is given. The promise resolves with
  18. * a {@link Process} object.
  19. *
  20. * @see {@link normalizeArgs} for argument details
  21. */
  22. function async () {
  23. // Normalize the function arguments
  24. let { command, args, options, callback, error } = normalizeArgs(arguments);
  25. return maybe(callback, new Promise((resolve, reject) => {
  26. if (error) {
  27. // Invalid arguments
  28. normalizeResult({ command, args, options, error });
  29. }
  30. else {
  31. let spawnedProcess;
  32. try {
  33. // Spawn the program
  34. spawnedProcess = spawn(command, args, options);
  35. }
  36. catch (error) {
  37. // An error occurred while spawning the process
  38. normalizeResult({ error, command, args, options });
  39. }
  40. let pid = spawnedProcess.pid;
  41. let stdout = options.encoding === "buffer" ? Buffer.from([]) : "";
  42. let stderr = options.encoding === "buffer" ? Buffer.from([]) : "";
  43. spawnedProcess.stdout && spawnedProcess.stdout.on("data", (data) => {
  44. if (typeof stdout === "string") {
  45. stdout += data.toString();
  46. }
  47. else {
  48. stdout = Buffer.concat([stdout, data]);
  49. }
  50. });
  51. spawnedProcess.stderr && spawnedProcess.stderr.on("data", (data) => {
  52. if (typeof stderr === "string") {
  53. stderr += data.toString();
  54. }
  55. else {
  56. stderr = Buffer.concat([stderr, data]);
  57. }
  58. });
  59. spawnedProcess.on("error", (error) => {
  60. try {
  61. normalizeResult({ error, command, args, options, pid, stdout, stderr });
  62. }
  63. catch (error) {
  64. reject(error);
  65. }
  66. });
  67. spawnedProcess.on("exit", (status, signal) => {
  68. try {
  69. resolve(normalizeResult({ command, args, options, pid, stdout, stderr, status, signal }));
  70. }
  71. catch (error) {
  72. reject(error);
  73. }
  74. });
  75. }
  76. }));
  77. }