【问题标题】:Ask users to input value for npm script要求用户输入 npm 脚本的值
【发布时间】:2021-07-12 23:47:00
【问题描述】:

我有一个 npm 脚本,它是这样运行的:

npm run start:local -- -target.location https://192.1.1.1:8052/

URL 参数是用户的本地 IP。

我希望让用户输入这个值,因为每个人都不同。

有可能吗?使用 vanila npm 脚本会很棒。

【问题讨论】:

  • 这能回答你的问题吗? Sending command line arguments to npm script
  • 不,它没有(或者至少我找不到它建议如何要求用户输入参数)。
  • 您可以从您的 npm 脚本中调用一个 bash 脚本,该脚本会从用户那里读取一个参数。有很多交互式 bash 脚本示例。
  • 但是在节点领域我希望必须以 URL=localhost npm run start 的方式运行它
  • package.json 文件的“脚本”属性的内容是什么?

标签: npm


【解决方案1】:

使用readline 获取ip 值,然后使用exec 生成此进程。这是一个纯 JS 解决方案,与操作系统无关。

例子:

// package.json
"scripts": {
"start": "npm run start:local -- -target.location",
"prompt" "node prompt.js"
},

// prompt.js

const { spawn, execSync } = require('child_process');
const exec = commands => {
  execSync(commands, { stdio: 'inherit', shell: true });
};
const spawnProcess = commands => {
  spawn(commands, { stdio: 'inherit', shell: true });
};
   const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('What is your current ip? example: https://192.168.1.10:9009 ', (ip) => {
  console.log(`Starting server on: ${ip}`);
  exec(`npm run start -- ${ip}`);
  rl.close();
});

【讨论】:

    【解决方案2】:

    如果您试图要求用户输入他们的响应,您可以这样做。

    const readline = require("readline");
    
    const reader = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        error: process.stderr
    });
    
    const ask = (message, default_value = null) => new Promise(resolve => {
        reader.question(message, (response)=>{
            return resolve(response.length >= 1 ? response : default_value);
        });
    });
    
    (()=>{
        let ip = await ask(`Please enter your public ip: `);
    })();
    

    【讨论】:

      【解决方案3】:

      使用 Node 的readline?它有交互式 IO 的方法。

      【讨论】:

        【解决方案4】:

        简单地说,npm script 将在您的 shell 环境中运行所需的命令。

        在 shell 脚本中,可以使用 $N 访问传递的参数,其中 N = 参数的位置。

        谈到你的情况,你要运行的命令是 npm run start:local -- -target.location USER_INPUT USER_INPUT 需要替换为用户传递的参数。假设用户将位置作为第一个参数传递给脚本,则可以使用$1 访问它。

        我创建了this gist 来演示同样的内容。

        您可以清楚地看到,我已经定义了start:local 来访问第一个参数,然后将其传递给start 脚本,然后该脚本会回显传入的参数。

        更新: 这是以提示格式向用户询问值的脚本。

        基本上,首先我要求用户输入,然后将其存储在变量中并将变量作为参数传递给npm start

        参考

        【讨论】:

        • 据我了解,代码不会要求用户输入一些值。我是不是错过了什么?
        • 我明白了。所以,你想要一个提示而不是将位置作为参数传递,对吧?
        • 答案已更新为包含“ASK”功能。
        • 看起来您的解决方案需要一些 bash 脚本(“读取位置”命令是否运行某种 bash 脚本?)。我很想避免它并使用 vanila npm(如果可能的话)。
        • 不,它不是 bash 脚本。接受来自stdin 的输入是一种 bash 语法。但是,我相信您的问题是关于 Windows 用户的担忧。在这种情况下,我建议在a bash environment accessible using git-bash 中运行所有npm scripts
        猜你喜欢
        • 2014-04-08
        • 1970-01-01
        • 2013-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-15
        • 2010-12-08
        相关资源
        最近更新 更多