7.10 创建子程序

2021-08-05  本文已影响0人  9e8aeff1c70c

概念

简单例子

此示例相当于从命令行运行命令‘ECHO hello’

/**
 * subprocess_simple.ts
 */

// create subprocess
const p = Deno.run({
  cmd: ["echo", "hello"],
});

// await its completion
await p.status();

运行它:

$ deno run --allow-run ./subprocess_simple.ts
hello

安全

创建子流程需要有--Allow-run权限。请注意,子进程不在Deno沙箱中运行,因此具有与您自己从命令行运行命令相同的权限。

和子程序通信

默认情况下,使用Deno.run()时,子进程会继承父进程的stdinstdoutstderr。如果您想与Started子进程通信,可以使用“Piped”选项。

/**
 * subprocess.ts
 */
const fileNames = Deno.args;

const p = Deno.run({
  cmd: [
    "deno",
    "run",
    "--allow-read",
    "https://deno.land/std@0.95.0/examples/cat.ts",
    ...fileNames,
  ],
  stdout: "piped",
  stderr: "piped",
});

const { code } = await p.status();

// Reading the outputs closes their pipes
const rawOutput = await p.output();
const rawError = await p.stderrOutput();

if (code === 0) {
  await Deno.stdout.write(rawOutput);
} else {
  const errorString = new TextDecoder().decode(rawError);
  console.log(errorString);
}

Deno.exit(code);

当你运行它:

$ deno run --allow-run ./subprocess.ts <somefile>
[file content]

$ deno run --allow-run ./subprocess.ts non_existent_file.md

Uncaught NotFound: No such file or directory (os error 2)
    at DenoError (deno/js/errors.ts:22:5)
    at maybeError (deno/js/errors.ts:41:12)
    at handleAsyncMsgFromRust (deno/js/dispatch.ts:27:17)
上一篇 下一篇

猜你喜欢

热点阅读