Node.js CLI应用:如何将--url选项值传入Wget命令参数
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

