子进程衍生:使用子进程运行其他文件
在 Github 上编辑
一个使用 CLI 标志衍生子进程来运行指定文件的示例。
import { parseArgs } from "jsr:@std/cli";
使用标准库中的 parseArgs 函数获取文件名。如果没有提供文件,则退出并显示错误。
import { expandGlob } from "jsr:@std/fs";
const flags = parseArgs(Deno.args, {
string: ["file"],
default: {
file: "",
},
});
if (!flags.file) {
console.error("No file provided");
Deno.exit(1);
}
使用 expandGlob 查找所有与提供的文件名匹配的文件。
const FilesList = await Array.fromAsync(
expandGlob(`**/*${flags.file}*`, { root: "." }),
);
const files = FilesList.filter((files) => files.name.includes(flags.file));
如果没有找到文件,则退出并显示错误。
if (files.length === 0) {
console.error("No files found");
Deno.exit(1);
}
如果找到多个文件,则退出并显示错误。
if (files.length > 1) {
console.error("Multiple files found");
Deno.exit(1);
}
const file = files[0];
使用 Deno.Command 类创建一个新命令,该命令将运行指定的文件。
const command = new Deno.Command(Deno.execPath(), {
args: [file?.path],
});
尝试衍生命令并捕获可能发生的任何错误。等待子进程完成并记录退出代码。
try {
const child = command.spawn();
child.ref();
} catch (error) {
console.error("Error while running the file: ", error);
Deno.exit(4);
}
使用 Deno CLI 在本地运行 此示例
deno run --allow-net --allow-run --allow-read https://docs.deno.org.cn/examples/scripts/subprocess_running_files.ts