新人求教如何在终端获得输入?

2022-12-05 19:17:52 +08:00
 SeleiXi
网上搜了好多,基本都不管用。最后就卡在运行而且能输入(但没有指定的输入提示),输入之后就报错 Uncaught ReferenceError ReferenceError: asd is not defined at <anonymous> (repl:1:1)
5547 次点击
所在节点    Node.js
7 条回复
yhxx
2022-12-05 19:48:27 +08:00
fzdwx
2022-12-05 20:03:46 +08:00
`asd is not defined ` 你换个 `ls` 什么的试试?
Albertcord
2022-12-05 22:24:59 +08:00
可以看下文档:
https://nodejs.org/dist/latest-v18.x/docs/api/process.html#processargv
本质上是类似于获取 shell 的输入,也就是一个标准流的输入
li1218040201
2022-12-05 22:39:49 +08:00
不知道你是想获取哪种,我理解有两种,一种是在终端执行一个命令后,获取到这个命令的输入;第二种是在终端进行交互式的输入,可以实时获取到输入。
直接给两种实现的代码吧

```typescript
// 1 、获取执行命令时的参数
const commandSegments = process.argv;
console.log(commandSegments);

/**
* @example
* node index.js run --help
* commandSegments === ['/usr/local/bin/node', '/Users/litao/Documents/temp/cmd/index.js', 'run', '--help'];
*/

// 2 、交互式获取输入的参数
const { createInterface } = require("readline");
const { stdin, stdout } = process;
console.log("Please input something:");
const rl = createInterface({
input: stdin,
output: stdout,
});
rl.on("line", async (input) => {
console.log("your input is:", input);
});

/**
* @example
* node index.js
* > hello world
* > your input is: hello world
*/

```

首先是运行这个脚本,我用 `node index.js run --help`,首先会打印

```bash
[
'/usr/local/bin/node',
'/Users/litao/Documents/temp/cmd/index.js',
'run',
'--help'
]
```

这个就是 `process.argv` 了,就是上面说的第一种;然后命令不会退出,这时可以继续输入,比如 `aaa`,终端会响应

```bash
your input is: aaa
```
tearnarry
2022-12-08 11:02:23 +08:00
在 Node.js 中,可以使用 readline 模块来实现交互式的输入。该模块提供了一个接口,可以从命令行读取用户输入的一行文本。例如,以下代码演示了如何使用 readline 模块来获取用户在终端中输入的文本:

Copy code
const readline = require('readline');

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

rl.question('请输入文本: ', (answer) => {
// 在这里处理用户输入的文本
console.log(`您输入的文本是: ${answer}`);

rl.close();
});
上面的代码创建了一个 readline 接口,然后使用 question 方法向用户询问一个问题,并在用户输入文本后处理该文本。

需要注意的是,readline 模块只能在 Node.js 环境下使用,如果要在浏览器中实现交互式输入,则需要使用其他方式。
Dogxi
2022-12-14 09:51:00 +08:00
推荐 inquirer (交互)或者 commander (单命令)
Dogxi
2022-12-14 09:53:42 +08:00
一个 inquirer demo (我写的机器人框架
module.exports = async () => {
const config = await inquirer.prompt([
{
type: "number",
name: "account",
message: "Bot account >",
},
},
{
type: "input",
name: "admin",
message: "Bot admin >",
},
{
type: "list",
name: "login",
message: "login mode >",
choices: [
{ name: "password", value: 'pwd' },
{ name: "qrcode(same network)", value: 'qrcode' },
],
},
},
]);

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/900306

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX