如何从用户nodejs获取输入

时间:2019-07-01 20:29:41

标签: javascript node.js

我目前有以下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.

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

2 个答案:

答案 0 :(得分: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帖子以获取更多信息。

答案 1 :(得分:0)

使用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();
});