Creating CLI using NodeJS - Passing variable to exec linux command

101 views Asked by At

Im trying to create a simple CLI using nodejs and commander.js package.

The purpose of the CLI is to touch a new file

const program = require('commander');
const exec    = require('child_process').exec;

program.version('0.0.1')
       .description('Command Line Interface (CLI)');

program.command('make:controller <name>')
       .description('Add a new controller called <name>')
       .action(function (name) {
           exec("touch name");
       });

program.parse(process.argv);

Command: make:controller NewController

Linux: touch NewController

How do i pass in the name variable into the exec() command.


P.S (after i created the new file i also want to write something into it)

2

There are 2 answers

0
Brahma Dev On BEST ANSWER
const program = require('commander');
const exec    = require('child_process').exec;

program.version('0.0.1')
       .description('Command Line Interface (CLI)');

program.command('make:controller <name>')
       .description('Add a new controller called <name>')
       .action(function (name) {
           exec("touch " + name);//mind the space after touch
       });

program.parse(process.argv);
0
Md.Shahjalal On

Pass the variable in exec(name) as like.

program.command('make:controller <name>')
   .description('Add a new controller called <name>')
   .action(function (name) {
       exec(name);
   });