如何在 VS Code 控制台/终端上获取 javascript 用户输入并返回输入值

问题描述 投票:0回答:1

因此,在Python中,我们可以使用“input”函数将用户输入分配给变量。那么我们如何在 JavaScript 中获取用户输入呢? 如果我们使用html文件,我们可以使用prompt()函数,但是如果我想在文本编辑器中获取用户输入怎么办?我不想导入外部代码(如node.js)

关于如何实现这一点有什么想法吗?

var name = input("Enter your name here");

我尝试运行上面的代码,但它给了我一个语法错误。 这段代码实际上可以在 python 中运行。 我不想使用prompt(),因为我想从命令行获取用户输入。

javascript input user-input
1个回答
0
投票

您可以尝试使用此模块来完成您的任务https://nodejs.org/api/readline.html

import {
    stdin as input,
    stdout as output,
} from 'node:process';

const rl = readline.createInterface({ input, output });

const answer = await rl.question(
    'What do you think of Node.js? '
);

console.log(
    `Thank you for your valuable feedback: ${answer}`
);

rl.close();
© www.soinside.com 2019 - 2024. All rights reserved.