Deno 1.28.0 添加了一个新的 API 来运行 shell 命令:Deno.Command https://deno.land/api?s=Deno.Command (--allow-run
需要许可)
let cmd = new Deno.Command("echo", { args: ["hello world"] });
let { code, stdout, stderr } = await cmd.output();
// stdout & stderr are a Uint8Array
console.log(new TextDecoder().decode(stdout)); // hello world
更高级的用法:
const command = new Deno.Command(Deno.execPath(), {
args: [
"eval",
"console.log('Hello World')",
],
stdin: "piped",
stdout: "piped",
});
const child = command.spawn();
// open a file and pipe the subprocess output to it.
child.stdout.pipeTo(
Deno.openSync("output", { write: true, create: true }).writable,
);
// manually close stdin
child.stdin.close();
const status = await child.status;
const s = await c.status;
console.log(s);
该 API 取代了已弃用的Deno.run
旧答案:
为了运行 shell 命令,您必须使用Deno.run
,这需要--allow-run
权限。
有一个持续讨论 https://github.com/denoland/deno/issues/3378 to use --allow-all
而不是运行子进程
以下将输出到stdout
.
// --allow-run
const process = Deno.run({
cmd: ["echo", "hello world"]
});
// Close to release Deno's resources associated with the process.
// The process will continue to run after close(). To wait for it to
// finish `await process.status()` or `await process.output()`.
process.close();
如果你想存储输出,你必须设置stdout/stderr
to "piped"
const process = Deno.run({
cmd: ["echo", "hello world"],
stdout: "piped",
stderr: "piped"
});
const output = await process.output() // "piped" must be set
const outStr = new TextDecoder().decode(output);
/*
const error = await p.stderrOutput();
const errorStr = new TextDecoder().decode(error);
*/
process.close();