DAILY DOCDAILY DOC
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
  • node

    • NODE
    • parseArgs
    • compose
    • date-format
    • dayjs
    • encrypt
    • env-cmd
    • glob
    • Koa 洋葱模型
    • lodash
    • logger
    • log4js
    • mongod
    • nanoid
    • node-red
    • node-stream
    • node:test
    • nodemailer
    • nodemon
    • nodered
    • parse-curl
    • pm2
    • toml
    • ws
    • yargs
    • zx

parseArgs

Nodejs 命令行参数解析

const { parseArgs } = require('util');

const args = [
  '-n',
  'alice',
  '-c',
  1,
  '--d=2',
  '--count=5',
  '-f',
  'F',
  '-f',
  'G',
  'file1',
  'file2'
];
// 定义选项
const options = {
  help: { type: 'boolean', short: 'h' },
  version: { type: 'boolean', short: 'v' },
  name: { type: 'string', short: 'n', default: 'Guest' },
  count: { type: 'string', short: 'c', default: '1' },
  limit: { type: 'string', short: 'l', default: '2' },
  flag: { type: 'string', short: 'f', default: ['ff'], multiple: true }
};

// 解析命令行参数
const res = parseArgs({
  args: args,
  options,
  strict: false
});
function log(...args) {
  console.log(`[${new Date().toLocaleTimeString()}]:`, ...args);
}
log('res', res);
const { values, positionals } = res;
if (values.help) {
  console.log('Usage: node script.js [options] [files...]');
  console.log('Options:');
  console.log('  -h, --help     Show help');
  console.log('  -v, --version  Show version');
  console.log('  -n, --name     Specify name (default: Guest)');
  console.log('  -c, --count    Specify count (default: 1)');
  process.exit(0);
}

if (values.version) {
  log('Version 1.0.0');
  process.exit(0);
}

Last Updated:
Contributors: rosendo
Prev
NODE
Next
compose