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

后端 未结 30 3449
梦如初夏
梦如初夏 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:24

    TypeScript solution with no libraries:

    interface IParams {
      [key: string]: string
    }
    
    function parseCliParams(): IParams {
      const args: IParams = {};
      const rawArgs = process.argv.slice(2, process.argv.length);
      rawArgs.forEach((arg: string, index) => {
        // Long arguments with '--' flags:
        if (arg.slice(0, 2).includes('--')) {
          const longArgKey = arg.slice(2, arg.length);
          const longArgValue = rawArgs[index + 1]; // Next value, e.g.: --connection connection_name
          args[longArgKey] = longArgValue;
        }
        // Shot arguments with '-' flags:
        else if (arg.slice(0, 1).includes('-')) {
          const longArgKey = arg.slice(1, arg.length);
          const longArgValue = rawArgs[index + 1]; // Next value, e.g.: -c connection_name
          args[longArgKey] = longArgValue;
        }
      });
      return args;
    }
    
    const params = parseCliParams();
    console.log('params: ', params);
    

    Input: ts-node index.js -p param --parameter parameter

    Output: { p: 'param ', parameter: 'parameter' }

提交回复
热议问题