English 中文(简体)
是否有一个相当于沙捞取 no的模块?
原标题:Is there a module equivalent of Python s argparse for node.js?

rel=“noretinger”/argparse for python使处理指挥线投入、处理立场论点、任择论点、旗帜、投入鉴定和更多工作迅速而容易。 I ve在Node.js开始撰写申请,Im认为,用人工书写所有申请是浪费时间的。

有没有处理这一问题的节点。

最佳回答
问题回答

有一个 直接港口,方便地也称为“Argparse”。

183.0 no已把核心添加到<代码>。

详细文件见

There s yargs, which seems to be pretty complete and well documented.

这里有一些简单的碎石代码,允许你提供点名:

const parse_args = () => {
    const argv = process.argv.slice(2);
    let args = {};
    for (const arg of argv){
        const [key,value] = arg.split("=");
        args[key] = value;
    }
    return args;
}

const main = () => {
    const args = parse_args()
    console.log(args.name);
}

例常使用:

# pass arg name equal to monkey
node arg_test.js name=monkey
# Output
>> monkey

也可增加<条码>。 姓名:

const parse_args = (valid_args) => {
    const argv = process.argv.slice(2);
    let args = {};
    let invalid_args = [];
    for (const arg of argv){
        const [key,value] = arg.split("=");
        if(valid_args.has(key)){
            args[key] = value;  
        } else {
            invalid_args.push(key);
        }       
    }
    if(invalid_args.length > 0){
        throw new Exception(`Invalid args ${invalid_args} provided`);
    } 
    return args;
}

const main = () => {
    const valid_args = new Set(["name"])
    const args = parse_args(valid_args)
    console.log(args.name);
}

这里的例子有:Node 18 s util.parseArgs 图书馆:

import path from  node:path 
import url from  node:url 
import util from  node:util 

const __filename = url.fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// Parse arguments
const {
  values: {
    quiet: quietMode
  },
} = util.parseArgs({
  args: process.argv.slice(2),
  options: {
    quiet: {
      type:  boolean ,
      short:  q ,
    },
  },
})

console.log( Quiet mode: , quietMode); // Usage: node ./script.mjs [-q|--quiet]

ArgumentParser wrapper class

I wrote a wrapper that acts very similar to the argparse library in Python. Any option that does not actually get passed to the internal util.parseArgs is added to a private Map and fetched when displaying the help.

<>说明: 这是一份 Python光版的Sharma <代码>argparse图书馆,因此没有完成。

/* eslint-disable no-console */
/* eslint-disable @typescript-eslint/no-unused-vars */

import path from  node:path 
import url from  node:url 
import util from  node:util 

const __filename = url.fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const capitalize = (s) => s[0].toUpperCase() + s.slice(1)

class CaseConverter {
  constructor() {}
  transform(_input) {
    throw new Error( Not implemented )
  }
  toCamelCase(input) {
    const [head, ...rest] = this.transform(input)
    return head + rest.map(capitalize).join(  )
  }
  toUpperSnakeCase(input) {
    return this.transform(input)
      .map((s) => s.toUpperCase())
      .join( _ )
  }
}

class CamelCaseConverter extends CaseConverter {
  constructor() {
    super()
  }
  transform(input) {
    return input.split(/(?=[A-Z])/)
  }
}

class KebabCaseConverter extends CaseConverter {
  constructor() {
    super()
  }
  transform(input) {
    return input.split( - )
  }
}

const camelCaseConv = new CamelCaseConverter()
const kebabCaseConv = new KebabCaseConverter()

class ArgumentParser {
  constructor(options) {
    const opts = { ...ArgumentParser.DEFAULT_OPTIONS, ...options }
    this.prog = opts.prog
    this.usage = opts.usage
    this.description = opts.description
    this.epilog = opts.epilog
    this.arguments = []
    this.helpMap = new Map()
    this.metavarMap = new Map()
  }
  addArgument(...args) {
    if (args.length === 0) {
      throw new Error( No argument supplied )
    }
    let options = {}
    if (typeof args.slice(-1) ===  object ) {
      options = args.pop()
    }
    if (args.length === 0) {
      throw new Error( No name or flag argument supplied )
    }
    this.#addInternal(args, options)
  }
  #addInternal(nameOrFlags, options) {
    let longName, shortName
    for (let nameOrFlag of nameOrFlags) {
      if (/^--w[w-]+$/.test(nameOrFlag)) {
        longName = kebabCaseConv.toCamelCase(nameOrFlag.replace(/^--/,   ))
      } else if (/^-w$/.test(nameOrFlag)) {
        shortName = kebabCaseConv.toCamelCase(nameOrFlag.replace(/^-/,   ))
      }
    }
    if (!longName) {
      throw new Error( A long name must be provided )
    }

    if (options.type !==  boolean ) {
      this.metavarMap.set(longName, options.metavar || camelCaseConv.toUpperSnakeCase(longName))
    }

    this.arguments.push({
      long: longName,
      short: shortName,
      default: options.default,
      type: options.type,
    })
    if (options.help) {
      this.helpMap.set(longName, options.help)
    }
  }
  #wrapText(text) {
    return wordWrap(text.trim().replace(/
/g,    ).replace(/s+/g,    ), 80,  
 )
  }
  #getScriptName() {
    return path.basename(process.argv[1])
  }
  #buildHelpMessage(options) {
    let helpMessage =   

    const flags = Object.entries(options)
      .map(([long, option]) => {
        return [options.short ? `-${option.short}` : `--${long}`, this.metavarMap.get(long)].filter((o) => o).join(   )
      })
      .join(   )

    helpMessage += `usage: ${this.prog ?? this.#getScriptName()} [${flags}]

`
    if (this.description) {
      helpMessage += this.#wrapText(this.description) +  

 
    }
    helpMessage +=  options:
 

    const opts = Object.entries(options).map(([long, option]) => {
      const tokens = [`--${long}`]
      if (option.short) {
        tokens[0] += `, -${option.short}`
      }
      if (option.type) {
        tokens.push(option.type)
      }
      return [tokens.join(   ), this.helpMap.get(long) ??   ]
    })

    const leftPadding = Math.max(...opts.map(([left]) => left.length))

    helpMessage +=
      opts
        .map(([left, right]) => {
          return left.padEnd(leftPadding,    ) +      + right
        })
        .join( 
 ) +  

 

    if (this.epilog) {
      helpMessage += this.#wrapText(this.epilog)
    }
    return helpMessage
  }
  parseArgs(args) {
    const options = this.arguments.concat(ArgumentParser.defaultHelpOption()).reduce((opts, argument) => {
      opts[argument.long] = {
        type: argument.type,
        short: argument.short,
        default: argument.default,
      }
      return opts
    }, {})

    const result = util.parseArgs({ args, options })

    if (result.values.help === true) {
      console.log(this.#buildHelpMessage(options))
      process.exit(0)
    }

    return result
  }
}

ArgumentParser.defaultHelpOption = function () {
  return {
    long:  help ,
    short:  h ,
    type:  boolean ,
  }
}

ArgumentParser.DEFAULT_OPTIONS = {
  prog: null, // The name of the program (default: os.path.basename(sys.argv[0]))
  usage: null, // The string describing the program usage (default: generated from arguments added to parser)
  description:   , // Text to display before the argument help (by default, no text)
  epilog:   , // Text to display after the argument help (by default, no text)
}

/**
 * Wraps a string at a max character width.
 *
 * If the delimiter is set, the result will be a delimited string; else, the lines as a string array.
 *
 * @param {string} text - Text to be wrapped
 * @param {number} [maxWidth=80] - Maximum characters per line. Default is `80`
 * @param {string | null | undefined} [delimiter=null] - Joins the lines if set. Default is `null`
 * @returns {string | string[]} - The joined lines as a string, or an array
 */
function wordWrap(text, maxWidth = 80, delimiter = null) {
  let lines = [],
    found,
    i
  while (text.length > maxWidth) {
    found = false
    // Inserts new line at first whitespace of the line (right to left)
    for (i = maxWidth - 1; i >= 0 && !found; i--) {
      if (/s/.test(text.charAt(i))) {
        lines.push(text.slice(0, i))
        text = text.slice(i + 1)
        found = true
      }
    }
    // Inserts new line at maxWidth position, since the word is too long to wrap
    if (!found) {
      lines.push(text.slice(0, maxWidth - 1) +  - ) // Hyphenate
      text = text.slice(maxWidth - 1)
    }
  }
  if (text) lines.push(text)
  return delimiter ? lines.join(delimiter) : lines
}

Usage

const argParser = new ArgumentParser({
  description: `this description
    was indented weird
        but that is okay`,
  epilog: `
      likewise for this epilog whose whitespace will
    be cleaned up and whose words will be wrapped
    across a couple lines`,
})

argParser.addArgument( -p ,  --profile , { type:  string , help:  environment profile  })
argParser.addArgument( -q ,  --quiet , { type:  boolean , default: false, help:  silence logging  })

const args = argParser.parseArgs(process.argv.slice(2))
const { values } = args
const { profile, quiet: quietMode } = values

console.log( Profile: , profile)
console.log( Quiet mode: , quietMode) // Usage: node ./script.mjs [-q|--quiet]

Output

$ node scripts/quietMode.mjs --help
usage: quietMode.mjs [--profile PROFILE --quiet --help]

this description was indented weird but that is okay

options:
--profile, -p string  environment profile
--quiet, -q boolean   silence logging
--help, -h boolean

likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines
$ node scripts/quietMode.mjs -p foo
Profile: foo
Quiet mode: false

我撰写了自己的案件转换战略:kebab-case, camelCase, and UPPER_SNAKE_CASE(也称为SCREAMING_SNAKE_CASE),但你可以读到js-convert-case。 npm模块相反。





相关问题
Working with modules in IntelliJ IDEA

As I understand, using modules allows us to control some dependencies. I mean that we can allow one module to interact with another one but not vise versa. We also can make some reusable things and ...

Module import path

I m unable to test-run a cssparser that I d like to use. test.py: from css.parse import parse data = """ em { padding: 2px; margin: 1em; border-width: medium; border-style: ...

Problem modulating action script project

I am refactoring a hugh action script solution in Flash builder (beta 2) using the flex 4 sdk. The project does NOT use the mx framework. What i want to have is: A big MAIN project several small ...

Test modules with Test::Unit

I encountered a problem when trying to test a module with Test::Unit. What I used to do is this: my_module.rb: class MyModule def my_func 5 # return some value end end test_my_module.rb: ...

Drupal section accessible by role

I need to limit access of content on Drupal site based on the Drupal User s Role. http://site.com/managers/intro http://site.com/managers/reviews http://site.com/managers/up-for-raises The ...

How to find where a function was imported from in Python?

I have a Python module with a function in it: == bar.py == def foo(): pass == EOF == And then I import it into the global namespace like so: from bar import * So now the function foo is ...

How to wire two modules in Verilog?

I have written two modules DLatch and RSLatch and i want to write verilog code to join those two.

热门标签