如何在 Javascript (NodeJs) 中获取用户输入?

发布: (2025年12月10日 GMT+8 14:48)
2 min read
原文: Dev.to

Source: Dev.to

使用 prompt‑sync

Node.js 没有内置的同步读取终端输入的方法,因此通常会使用像 prompt‑sync 这样的外部库。

安装

npm install prompt-sync

在终端(例如 VS Code 集成终端)中于项目目录下运行上述命令。

基本用法

// Import the library and create a prompt function
const prompt = require('prompt-sync')();

// Ask the user for input
const userInput = prompt('Enter your name: ');

// Output the entered value
console.log(userInput);

程序运行时,会显示提示文字(Enter your name:)。
如果用户输入 David 并按下 Enter,程序会输出:

David

这种方法提供了一种简单的同步方式,从 Node.js 终端读取用户输入。


使用 readline(简要说明)

内置的 readline 模块也可以用来读取输入,但它是异步的,对初学者来说可能稍显复杂。现在,prompt‑sync 提供了更容易的入门方式。等你对基础掌握得更熟练后,可以再去探索 readline

Back to Blog

相关文章

阅读更多 »

不要让你的 bundles 超重

说实话:我们都在乎 bundle size。多年来,bundlesize 是首选工具,但它现在已经过时且不再维护。安全检查开始标记…