li1218040201 最近的时间轴更新
li1218040201

li1218040201

V2EX 第 410043 号会员,加入于 2019-05-07 20:57:19 +08:00
li1218040201 最近回复了
2022-12-05 22:39:49 +08:00
回复了 SeleiXi 创建的主题 Node.js 新人求教如何在终端获得输入?
不知道你是想获取哪种,我理解有两种,一种是在终端执行一个命令后,获取到这个命令的输入;第二种是在终端进行交互式的输入,可以实时获取到输入。
直接给两种实现的代码吧

```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
```
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1007 人在线   最高记录 6543   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 11ms · UTC 18:51 · PVG 02:51 · LAX 11:51 · JFK 14:51
Developed with CodeLauncher
♥ Do have faith in what you're doing.