You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js CLI应用:如何将--url选项值传入Wget命令参数

Fixing Variable Substitution Error in Node.js CLI with commander.js and child_process.exec

Looks like you're hitting a classic JavaScript string interpolation snag here! Let's break down what's going wrong and how to fix it quickly.

The Issue

When you run node app.js --url ff99cc.art, you get this error output:

error: Command failed: wget ${options.url}
/bin/bash: line 1: ${options.url}: bad substitution

This happens because your code uses double quotes for the exec command string:

exec("wget ${options.url}", (error, stdout, stderr) => {

JavaScript doesn't process variable interpolation (${} syntax) inside double-quoted strings—those placeholders get passed directly to the shell, which can't recognize them as valid syntax, hence the "bad substitution" error.

The Fix

Switch the double quotes to backticks (`), which are JavaScript template literals. Template literals natively support embedding variables directly into strings using ${}:

#!/usr/bin/env node
'use strict';

const commander = require('commander');
const { exec } = require("child_process");
const program = new commander.Command();

program
  .option('-u, --url <value>', 'Website address');

program.parse(process.argv);

const options = program.opts();

if (options.url) {
        // Use backticks here for proper variable interpolation
        exec(`wget ${options.url}`, (error, stdout, stderr) => {
            if (error) {
                console.log(`error: ${error.message}`);
                return;
            }
            if (stderr) {
                console.log(`stderr: ${stderr}`);
                return;
            }
            console.log(`stdout: ${stdout}`);
        });
}

Now when you run node app.js --url ff99cc.art, the options.url value will be correctly inserted into the wget command, executing wget ff99cc.art as intended.

A Quick Security Note

Just a heads-up: using exec() with user-provided input (like the --url value here) carries a shell injection risk if you don't sanitize the input. For production code, consider using execFile() instead—it doesn't spawn a shell and passes arguments directly to the command, which is safer for untrusted input:

const { execFile } = require("child_process");

// ...

execFile('wget', [options.url], (error, stdout, stderr) => {
    // Same callback logic here
});

This way, the URL is treated as a direct argument to wget, avoiding any potential malicious shell command execution.

内容的提问来源于stack exchange,提问作者user21008370

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 10:05:26