我想从 Deno 运行任何任意的 bash 命令,就像我在 Node.js 中使用的一样child_process。这在 Deno 中可能吗?
Mar*_*nde 13
为了运行 shell 命令,您必须使用Deno.run,这需要--allow-run权限。
有一个正在进行的讨论可以用来--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();
Run Code Online (Sandbox Code Playgroud)
如果要存储输出,则必须设置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();
Run Code Online (Sandbox Code Playgroud)
确保await status或output使用Deno.run.
否则,该进程可能会在执行任何代码之前被终止。例如:
deno run --allow-run main.ts
Run Code Online (Sandbox Code Playgroud)
main.ts:
deno run --allow-run main.ts
Run Code Online (Sandbox Code Playgroud)
child.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();
Run Code Online (Sandbox Code Playgroud)
stdin/传递参数stdout:// 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);
Run Code Online (Sandbox Code Playgroud)
child.ts:
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 */ }
Run Code Online (Sandbox Code Playgroud)
Deno docs 中还有一个很好的示例资源。
| 归档时间: |
|
| 查看次数: |
3410 次 |
| 最近记录: |