Containers 现已支持 exec()
exec() 现已用于 Containers。使用 this.ctx.container.exec() 在正在运行的 Container 中启动进程、流式传输标准输入和输出、检查退出状态码以及向每个进程发送信号。
在继承 Container 的类中,或在另一个 Durable Object 中通过 this.ctx.container 调用 exec()。关联的 Container 必须已在运行。
此示例在需要时启动 Container,然后读取其 Node.js 版本:
import { Container } from "@cloudflare/containers";
export class MyContainer extends Container {
async readVersion() {
if (!this.ctx.container.running) {
await this.start();
}
const process = await this.ctx.container.exec(["node", "--version"]);
const output = await process.output();
const decoder = new TextDecoder();
return {
exitCode: output.exitCode,
stdout: decoder.decode(output.stdout),
stderr: decoder.decode(output.stderr),
};
}
}import { Container } from "@cloudflare/containers";
export class MyContainer extends Container {
async readVersion() {
if (!this.ctx.container.running) {
await this.start();
}
const process = await this.ctx.container.exec(["node", "--version"]);
const output = await process.output();
const decoder = new TextDecoder();
return {
exitCode: output.exitCode,
stdout: decoder.decode(output.stdout),
stderr: decoder.decode(output.stderr),
};
}
}命令数组直接启动可执行文件,没有隐式的 shell。如果需要管道、重定向或变量展开,请显式调用 shell。
一个 RPC 方法可以在一次调用者到 Durable Object 的往返中协调多个 exec() 调用。它还可以传递面向字节的 ReadableStream 输入或返回具有流量控制的流式输出。
有关选项和流式传输示例,请参阅执行命令。