Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass JSON as command line argument to Node

Tags:

node.js

I'd like to pass a JSON object as a command line argument to node. Something like this:

node file.js --data { "name": "Dave" }

What's the best way to do this or is there another more advisable way to do accomplish the same thing?

like image 238
Evan Hobbs Avatar asked Sep 30 '15 22:09

Evan Hobbs


2 Answers

this works for me:

$ node foo.js --json-array='["zoom"]'

then in my code I have:

  import * as _ from 'lodash';

  const parsed = JSON.parse(cliOpts.json_array || []);

  _.flattenDeep([parsed]).forEach(item => console.log(item));

I use dashdash, which I think is the best choice when it comes to command line parsing.

To do the same thing with an object, just use:

$ node foo.js --json-object='{"bar": true}'
like image 76
Alexander Mills Avatar answered Oct 14 '22 03:10

Alexander Mills


if its a small amount of data, I'd use https://www.npmjs.com/package/minimist, which is a command line argument parser for nodejs. It's not json, but you can simply pass options like

--name=Foo 

or

-n Foo

I think this is better suited for a command line tool than json.

If you have a large amount of data you want to use you're better of with creating a json file and only pass the file name as command line argument, so that your program can load and parse it then.

Big objects as command line argument, most likely, aren't a good idea.

like image 5
baao Avatar answered Oct 14 '22 01:10

baao