【问题标题】:How to get input from user nodejs [duplicate]如何从用户nodejs获取输入[重复]
【发布时间】:2019-11-12 11:41:59
【问题描述】:

我目前有这个 nodejs 代码来检查网站服务器是启动还是关闭:

var http = require("http");
http.get({host: "nodejs.org"}, function(res){
   if( res.statusCode == 200 )
       console.log("This site is up and running!");
   else
       console.log("This site is down " + res.statusCode);
});

现在,我希望程序要求用户输入一个网站,然后它会检查该网站是打开还是关闭。我在这里尝试使用提示方法:

var website = prompt("Please enter the website server you would like to check", "google.com");

但是当我运行它时,我得到了这个错误:

ReferenceError: prompt is not defined
 at Object.<anonymous> (/Users/navania/WebstormProjects/untitled/UpOrDown.js:3:15)
 at Module._compile (internal/modules/cjs/loader.js:776:30)
 at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
 at Module.load (internal/modules/cjs/loader.js:653:32)
 at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
 at Function.Module._load (internal/modules/cjs/loader.js:585:3)
 at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
 at startup (internal/bootstrap/node.js:283:19)
 at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3).
I also tried using window.prompt as many other questions suggested, but that still gave me the same error except it says that window is not defined.

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • @IMustBeSomeone npmjs.com/package/prompt 需要的不仅仅是安装它......现有的代码将无法正常工作。
  • 嗯,不,它不会破坏它,就像它已经破坏了一样。但是安装后它仍然会损坏。你建议安装的那个 npm 包已经 3 年没有更新了。

标签: javascript node.js


【解决方案1】:

您想在哪个环境中使用此代码? 如果正确理解您的意思,您需要从命令行获取url 作为参数。为此,请查看以下代码:

var http = require("http");
var [url] = process.argv.slice(2);
console.log(url);
var request = http.get({ host: url }, function(res){
   if( res.statusCode == 200 || res.statusCode == 301 || res.statusCode == 302)
       console.log("This site is up and running!");
   else
       console.log("This site is down " + res.statusCode);
});
request.on('error', function(err) {
    console.log("This site is down");
});
request.end();
$ node index.js http://nodejs.com

我将您推荐给this 帖子以获取更多信息。

【讨论】:

  • 感谢您的回复。但是,我使用了此代码,当我在终端命令中运行 google.com 时,它表示该网站已关闭(状态代码为 400),尽管它当前已启动。任何想法为什么会这样?事实上,我输入的任何网站似乎都会返回状态码 400。
  • @oofmeister27 它适用于我的电脑。如果要检查http 以外的其他协议,则需要使用适当的模块,例如https 模块用于https 协议。为了摆脱这些东西,我建议你使用功能齐全的模块,例如request 或axios。
  • 嗯,我目前正在使用网络风暴,如果这有什么改变的话。我只想使用http协议。您能否发送一些您在计算机上执行的操作的屏幕截图?
  • 我目前正在使用命令“node UpOrDown.js google.com”,然后返回“This site is down 400”
  • @oofmeister27 google.com 将所有http 请求重定向到https,因此返回状态码301,它实际上不是200。您需要考虑状态码301。
【解决方案2】:

使用readline 模块。它带有nodejs。

来自docs的示例:

const readline = require('readline');

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

rl.question('What do you think of Node.js? ', (answer) => {
  console.log(`Thank you for your valuable feedback: ${answer}`);
  rl.close();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2011-12-13
    • 2018-06-12
    相关资源
    最近更新 更多