javascript 使用命令行中的节点“提示未定义”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24291909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:31:06  来源:igfitidea点击:

"prompt not defined" using node from command line?

javascriptnode.js

提问by user3753598

I'm trying to run a simple javascript program from the command line and am getting an unexpected error. prompt seems to be a simple javascript command; not sure why it's not defined.

我正在尝试从命令行运行一个简单的 javascript 程序,但出现意外错误。prompt 似乎是一个简单的 javascript 命令;不知道为什么它没有定义。

my test.js file:

我的 test.js 文件:

console.log("I will now ask you for your name.");
var name = prompt("Enter your name");
console.log("Hello ".concat(name, ". How are you"));

I'm running it like this:

我是这样运行的:

C:\directory\node test.js
I will now ask you for your name.

C:\directory\test.js:2
var name = prompt("Enter your name");

Reference Error: prompt is not defined

回答by soben360

you might wanna check this out as well but first run npm install prompt -- save

你可能也想看看这个,但首先运行 npm install prompt -- save

var prompt = require("prompt");
prompt.start();
console.log("I will now ask you for your name.");
prompt.get(["name"], function(err, res){
console.log("Hello ".concat(res.name, ". How are you"));
});

回答by azero0

I think you might be interested in this code :

我想你可能对这段代码感兴趣:

console.log("I will now ask you for your name.");
process.stdin.setEncoding('utf8');
var name;
process.stdin.on('readable', function() {
    name = process.stdin.read();
    if (name !== null) {
        console.log("Hello ".concat(name, ". How are you"));
        process.exit();
    }
});

this is the node.js way of doing what you need to do. Hope this helps!

这是 node.js 做你需要做的事情的方式。希望这可以帮助!