【发布时间】:2020-09-20 08:56:13
【问题描述】:
我想从 Deno 运行任意 bash 命令,就像我在 Node.js 中使用 child_process 一样。在 Deno 有可能吗?
【问题讨论】:
标签: deno
我想从 Deno 运行任意 bash 命令,就像我在 Node.js 中使用 child_process 一样。在 Deno 有可能吗?
【问题讨论】:
标签: deno
为了运行一个shell命令,你必须使用Deno.run,这需要--allow-run权限。
有一个ongoing discussion 可以使用--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 设置为 "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();
【讨论】:
确保使用Deno.run创建的子进程的awaitstatus或output。
否则,进程可能会在执行任何代码之前被终止。例如:
deno run --allow-run main.ts
main.ts:
const p = Deno.run({
cmd: ["deno", "run", "--allow-write", "child.ts"],
});
const { code } = await p.status(); // (*1); wait here for child to finish
p.close();
child.ts:
// If we don't wait at (*1), no file is written after 3 sec delay
setTimeout(async () => {
await Deno.writeTextFile("file.txt", "Some content here");
console.log("finished!");
}, 3000);
stdin/stdout传递参数:const p = Deno.run({
cmd: ["deno", "run", "--allow-write", "child.ts"],
// Enable pipe between processes
stdin: "piped",
stdout: "piped",
stderr: "piped",
});
if (!p.stdin) throw Error();
// pass input to child
await p.stdin.write(new TextEncoder().encode("foo"));
await p.stdin.close();
const { code } = await p.status();
if (code === 0) {
const rawOutput = await p.output();
await Deno.stdout.write(rawOutput); // could do some processing with output
} else { /* error */ }
child.ts:
import { readLines } from "https://deno.land/std/io/bufio.ts"; // convenient wrapper
// read given input argument
let args = "";
for await (const line of readLines(Deno.stdin)) {
args += line;
}
setTimeout(async () => {
await Deno.writeTextFile("file.txt", `Some content here with ${args}`);
console.log(`${args} finished!`); // prints "foo finished!""
}, 3000);
Deno docs 中还有一个很好的示例资源。
【讨论】:
您可以像这样使用run 做到这一点:
// myscript.js
Deno.run({
cmd: ["echo", "hello world"]
})
您必须在运行脚本时--allow-run 才能使其工作:
deno run --allow-run ./myscript.js
【讨论】:
--allow-all标志那里有--allow-run
或者,您也可以通过任务运行器调用shell命令,例如drake,如下所示
import { desc, run, task, sh } from "https://deno.land/x/drake@v1.5.0/mod.ts";
desc("Minimal Drake task");
task("hello", [], async function () {
console.log("Hello World!");
await sh("deno run --allow-env src/main.ts");
});
run();
$ deno run -A drakefile.ts hello
【讨论】: