Tom Tom - 4 months ago 15
Node.js Question

Getting the value from command line input, command-line-args NPM module, node.js/javascript

I use this code to add a -find flag, but I can't find how to get the value in a useable variable.

const commandLineArgs = require('command-line-args')
const quicksearch = [
{name: 'find', alias: 'f',type: String}
]


I'd like to achieve this in the terminal, -find=github, then use the value of the find flag, in a useable variable, so I can emit it to the server, I've read the docs but theres nothing about it.

Answer

Run at the command-promt/bash like:

node test.js -f github or

node test.js --find github or

node test.js --find=github

Expect Output:

{ find: 'github' }

Server/Javascript file (test.js):

var commandLineArgs = require('command-line-args')

const optionDefinitions = [
  { name: 'find', alias: 'f', type: String }
]

const options = commandLineArgs(optionDefinitions)

console.log(options);

//options.find will be equal to 'github'