Escape args before running spawn

This commit is contained in:
Sander Declerck 2025-09-24 14:29:49 +02:00
parent 534aeee457
commit 83141d375a
No known key found for this signature in database
3 changed files with 153 additions and 4 deletions

View file

@ -0,0 +1,38 @@
import { spawnSync, spawn } from "child_process";
function escapeArg(arg) {
// If argument contains spaces or quotes, wrap in double quotes and escape double quotes
if (arg.includes(" ") || arg.includes('"') || arg.includes("'")) {
return '"' + arg.replaceAll('"', '\\"') + '"';
}
return arg;
}
function buildCommand(command, args) {
const escapedArgs = args.map(escapeArg);
return `${command} ${escapedArgs.join(" ")}`;
}
export function safeSpawnSync(command, args, options = {}) {
const fullCommand = buildCommand(command, args);
return spawnSync(fullCommand, { ...options, shell: true });
}
export async function safeSpawn(command, args, options = {}) {
const fullCommand = buildCommand(command, args);
return new Promise((resolve, reject) => {
const child = spawn(fullCommand, { ...options, shell: true });
child.on("close", (code) => {
resolve({
status: code,
stdout: Buffer.from(""),
stderr: Buffer.from(""),
});
});
child.on("error", (error) => {
reject(error);
});
});
}