How do I pass command line arguments to a Node.js program?

后端 未结 30 3123
梦如初夏
梦如初夏 2020-11-22 04:03

I have a web server written in Node.js and I would like to launch with a specific folder. I\'m not sure how to access arguments in JavaScript. I\'m running node like this:

30条回答
  •  长发绾君心
    2020-11-22 04:26

    There's an app for that. Well, module. Well, more than one, probably hundreds.

    Yargs is one of the fun ones, its docs are cool to read.

    Here's an example from the github/npm page:

    #!/usr/bin/env node
    var argv = require('yargs').argv;
    console.log('(%d,%d)', argv.x, argv.y);
    console.log(argv._);
    

    Output is here (it reads options with dashes etc, short and long, numeric etc).

    $ ./nonopt.js -x 6.82 -y 3.35 rum
    (6.82,3.35)
    [ 'rum' ] 
    $ ./nonopt.js "me hearties" -x 0.54 yo -y 1.12 ho
    (0.54,1.12)
    [ 'me hearties', 'yo', 'ho' ]
    

提交回复
热议问题