【问题标题】:How to save configuration settings for my NodeJs CLI app?如何保存我的 NodeJs CLI 应用程序的配置设置?
【发布时间】:2020-08-21 06:14:58
【问题描述】:

我正在制作一个 nodejs 应用程序作为 cli 工具。我使用yargs 定义我的命令,我使用.config() 方法从.config 或config.json 文件加载默认配置设置,如下所示:

const findUp = require('find-up')
const fs = require('fs')
const yargs = require('yargs');

const configPath = findUp.sync(['.config', 'config.json']);
const config = configPath ? JSON.parse(fs.readFileSync(configPath)) : {};

yargs
    .command( require('./command/command-name'))
    .option( .... )
    .config( config )
    .argv

我想创建一个可用于配置我的 .config 文件的命令。比如:

my-tool configure --defaults key1=<value> key2=<value>

是否有可用的 npm 包来执行此操作,还是我必须自己推出?

【问题讨论】:

    标签: node.js command-line-interface


    【解决方案1】:

    我自己滚动。

    # configure.js
    const findUp = require('find-up')
    const fs = require('fs')
    
    exports.command = 'configure'
    exports.desc    = 'Set or view your configuration'
    exports.builder = {
        'defaults': {
            desc: 'set configuration values',
            type: 'array',
            group: 'Parameters:'
    
        }
    }
    exports.handler = function (argv) {
    
        const configPath = findUp.sync(['.config', 'config.json']);
        const config = configPath ? JSON.parse(fs.readFileSync(configPath)) : {};
    
        if (argv.defaults) {
            argv.defaults.map( arg => {
                var args = arg.split('=');
                if (args[1]) {
                    config[args[0]] = args[1];
                } else {
                    delete config[args[0]];
                }            
            })
    
            var file = configPath ? configPath : "./.config";
            fs.writeFileSync(file, JSON.stringify(config, null, 2));
        } else {
            console.log( JSON.stringify(config, null, 2));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-27
      • 1970-01-01
      • 2017-03-14
      • 2016-11-16
      • 2013-04-06
      • 1970-01-01
      • 2016-03-06
      • 2019-10-15
      • 2010-12-21
      相关资源
      最近更新 更多