Search code examples
node.jsnpmcommand-line-interfacenode-commander

CLI app on Node.js How to pass the option value as an argument for the Shell command via child_process


How to pass the value of the --url option as an argument for the Wget command

#!/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) {
        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}`);
        });
}

Output:

node app.js --url ff99cc.art
error: Command failed: wget ${options.url}
/bin/bash: line 1: ${options.url}: bad substitution

It is necessary that the --url value is passed as an argument for wget. So that when you execute the node command app.js --url example.com,she was doing wget example.com.

Solved Thanks spyrospal and ibrahim tanyalcin The issue is how you use string interpolation to format the wget command. As mentioned here should be with backtick (`) characters instead of double quotes:

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

Solution

  • The issue is how you use string interpolation to format the wget command. As mentioned here should be with backtick (`) characters instead of double quotes:

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