D
Deno

help

Usage of Deno.Command?

RRoXuS10/14/2023
Hey guys we use Deno.run to launch shell cmd and pipe the result to log. But Deno.run will be deprecated and I am not able to write a good equivalent with Deno.Command, do you have a suggestion? Here is my simple Deno.run:
import * as log from "https://deno.land/std@0.204.0/log/mod.ts";

export default async (
cmd: string,
args: Array<string>,
cwd?: string,
dry = false,
) => {
const logger = log.getLogger();
if (dry) {
logger.debug([`dry ${cwd} ${cmd}`, ...args].join(" "));
return Promise.resolve("");
}
logger.debug([cwd, cmd, ...args].join(" "));
const p = Deno.run({
cmd: [cmd, ...args],
cwd,
stdout: "piped",
stderr: "piped",
});

const [stderr, stdout, status] = await Promise.all([
p.stderrOutput(),
p.output(),
p.status(),
]);

p.close();

if (status.code === 0) {
return new TextDecoder().decode(stdout);
} else {
const errorString = new TextDecoder().decode(stderr);
throw new Error(
`\n${Deno.cwd()} ${cwd} ${cmd} ${args} ${errorString}`,
);
}
};
import * as log from "https://deno.land/std@0.204.0/log/mod.ts";

export default async (
cmd: string,
args: Array<string>,
cwd?: string,
dry = false,
) => {
const logger = log.getLogger();
if (dry) {
logger.debug([`dry ${cwd} ${cmd}`, ...args].join(" "));
return Promise.resolve("");
}
logger.debug([cwd, cmd, ...args].join(" "));
const p = Deno.run({
cmd: [cmd, ...args],
cwd,
stdout: "piped",
stderr: "piped",
});

const [stderr, stdout, status] = await Promise.all([
p.stderrOutput(),
p.output(),
p.status(),
]);

p.close();

if (status.code === 0) {
return new TextDecoder().decode(stdout);
} else {
const errorString = new TextDecoder().decode(stderr);
throw new Error(
`\n${Deno.cwd()} ${cwd} ${cmd} ${args} ${errorString}`,
);
}
};
if I use the example of Deno.Command, something like
const command = new Deno.Command(Deno.execPath(), {
args: [
"eval",
"console.log('hello'); console.error('world')",
],
});
const { code, stdout, stderr } = await command.output();
const command = new Deno.Command(Deno.execPath(), {
args: [
"eval",
"console.log('hello'); console.error('world')",
],
});
const { code, stdout, stderr } = await command.output();
It works but I have the log after total execution, I would like the log as execution progresses
DAHDeno AI Helper10/14/2023
Sure, I can help you with that. The Deno.Command class is used to create a child process. It has methods like output(), outputSync(), and spawn() to execute the command and collect its output. Here's how you can rewrite your function using Deno.Command:
import * as log from "https://deno.land/std@0.204.0/log/mod.ts";

export default async (
cmd: string,
args: Array<string>,
cwd?: string,
dry = false,
) => {
const logger = log.getLogger();
if (dry) {
logger.debug([`dry ${cwd} ${cmd}`, ...args].join(" "));
return Promise.resolve("");
}
logger.debug([cwd, cmd, ...args].join(" "));

const command = new Deno.Command(cmd, {
args,
cwd,
stdin: "piped",
stdout: "piped",
stderr: "piped",
});

const { code, stdout, stderr } = await command.output();

if (code === 0) {
return new TextDecoder().decode(stdout);
} else {
const errorString = new TextDecoder().decode(stderr);
throw new Error(
`\n${Deno.cwd()} ${cwd} ${cmd} ${args} ${errorString}`,
);
}
};
import * as log from "https://deno.land/std@0.204.0/log/mod.ts";

export default async (
cmd: string,
args: Array<string>,
cwd?: string,
dry = false,
) => {
const logger = log.getLogger();
if (dry) {
logger.debug([`dry ${cwd} ${cmd}`, ...args].join(" "));
return Promise.resolve("");
}
logger.debug([cwd, cmd, ...args].join(" "));

const command = new Deno.Command(cmd, {
args,
cwd,
stdin: "piped",
stdout: "piped",
stderr: "piped",
});

const { code, stdout, stderr } = await command.output();

if (code === 0) {
return new TextDecoder().decode(stdout);
} else {
const errorString = new TextDecoder().decode(stderr);
throw new Error(
`\n${Deno.cwd()} ${cwd} ${cmd} ${args} ${errorString}`,
);
}
};
Please note that the Deno.Command API is still unstable, so you need to run your script with the --unstable flag. Also, the Deno.Command class does not have a cwd option, so you might need to adjust your command and arguments to account for the working directory.
RRoXuS10/15/2023
No u can't use command.output with stdin to piped
Rry10/15/2023
@RoXuS You would use command.spawn()
RRoXuS10/15/2023
yes finally I have try :
import { log } from "../deps.ts";

export default async (
cmd: string,
args: Array<string>,
cwd?: string,
dry = false,
) => {
const logger = log.getLogger();
if (dry) {
logger.debug([`dry ${cwd} ${cmd}`, ...args].join(" "));
return Promise.resolve("");
}
logger.debug([cwd, cmd, ...args].join(" "));
const p = new Deno.Command(cmd, {
args,
cwd,
stdin: "piped",
stdout: "piped",
});

const child = p.spawn();

const status = await child.status;

if (status.code === 0) {
return Promise.resolve();
} else {
throw new Error(
`\n${Deno.cwd()} ${cwd} ${cmd} ${args}`,
);
}
};
import { log } from "../deps.ts";

export default async (
cmd: string,
args: Array<string>,
cwd?: string,
dry = false,
) => {
const logger = log.getLogger();
if (dry) {
logger.debug([`dry ${cwd} ${cmd}`, ...args].join(" "));
return Promise.resolve("");
}
logger.debug([cwd, cmd, ...args].join(" "));
const p = new Deno.Command(cmd, {
args,
cwd,
stdin: "piped",
stdout: "piped",
});

const child = p.spawn();

const status = await child.status;

if (status.code === 0) {
return Promise.resolve();
} else {
throw new Error(
`\n${Deno.cwd()} ${cwd} ${cmd} ${args}`,
);
}
};
And it is ok, I don't understand why the result are piped to the log but it works haha thx for your response!

Looking for more? Join the community!

Recommended Posts
When the destination server is down, WebSocketStream stops and the program crashes.I'm running the following code: ```const ws = new WebSocketStream("wss://localhost"); setInterval((Struggling with interactive FreshChartsHi there I'm trying to display charts in my fresh js project. i want to have them as islands accordiTurso with local db fileI wanted to try out Turso's syncURL feature and for that it creates a local db file to read from andImporting local NodeJS module from DenoIs it possible to import a javascript file that has `node` imports for standart modules like `http` how I can install antd in my deno project?how I can install antd in my deno project?Deno Fresh Twind ColorsJust a message to anyone using Deno Fresh and wondering why their tailwindcss colors aren't working-Can you run Deno.serve in a pooled thread mode?is there a way in Deno to run a http request in a separate thread?How do I rerender my island after a signal change?Hi there im trying to rerender this sidebar navigation when you toggle it, making it change size and'Relative import path not prefixed' error from @types/express .d.ts file?Converting an express mjs project to deno & TS, and running into an issue using code from this exampThe requested module 'test/jsx-runtime' does not provide an export named 'jsxs'hej, I have a exported function `jsx()` stored in `jsx-runtime.ts`. I also added these `deno.json` scompiled artifact can't find deno.jsonI'm using github actions to build and publish a binary like so ``` DENO_TLS_CA_STORE=system deno comysql query is skippedHi, I have a function that should retrieve data from the database and then process and return it. ThUsing in-memory KV (sqlite) in productionIs it ok to use the KV backed by a local SQLite database in production ? If not, could you explain wdeno.land servers not reachable / timeoutFor the past few days, I've been encountering timeouts when trying to load modules from deno.land/x.