Nodejs - passing commander arguments to forever-monitor child process

405 views Asked by At

I have this node cli script

#!/usr/bin/env node
const path = require('path');
const forever = require('forever-monitor');
const script = path.format({dir: __dirname, base: 'pager.js'});
const chalk = require('chalk');
const commander = require('commander');

commander.version('1.0.0')
.option('-m, --message', 'set awesome message')
.parse();

const args = commander.opts();

const header = `
+---------------------+  
| Awesome v1.0 |
+---------------------+
`;

const child = new (forever.Monitor)(script, {
    max: 2,
    silent: false,
    args: args
});

child.start();

child.on('start', (process) => {
    console.log(chalk.magenta.bold(header));
});

child.on('restart', () => {
    console.log(`Forever restarting script for ${child.times} time`);
});

child.on('exit:code', (code) => {
    console.log(`Forever detected script exited with code ${code}`);
});

I want to integrate commander togive the user the ability to pass arguments that will be parsed and then passed to the child process that is running until terminal is closed with the help of forever-monitor npm package. At the moment I've tried to use commander inside the child process but without success, it will be ignored. I've then moved it inside my index.js code but I don't know how to pass the arguments to the child process. At the moment I get this error if I pass the parsed arguments to the args option of forever monitor

host:awesome dev$ node . -m 'Hello!'
/Users/dev/Desktop/awesome/node_modules/forever-monitor/lib/forever-monitor/monitor.js:130
    this.args.unshift(script);
              ^

TypeError: this.args.unshift is not a function
    at new exports.Monitor (/Users/dev/Desktop/awesome/node_modules/forever-monitor/lib/forever-monitor/monitor.js:130:15)
    at Object.<anonymous> (/Users/dev/Desktop/awesome/index.js:20:15)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47

Can anyone give me some help about?

1

There are 1 answers

2
shadowspawn On BEST ANSWER

forever-monitor: the args configuration option passed to forever-monitor expects an array.

'args':    ['foo','bar']

Commander: program.opts() returns a regular javascript object which is a hash with the keys being the option names. program.args is an array of the parsed command-arguments with recognised options and option-values removed.

In Commander, also have a look at .allowUnknownOption() and passThroughOptions() so Commander allows unrecognised options on the command line. The default behaviour is to show an error for unrecognised options.