javascript - 如何从用户nodejs获取输入

标签 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.

如有任何帮助,我们将不胜感激。谢谢!

最佳答案

你想在什么环境下使用这段代码? 如果正确理解您的意思,您需要从命令行获取 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发布以获取更多信息。

关于javascript - 如何从用户nodejs获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56842061/

相关文章:

python - ubuntu npm install lib 错误与 node-expat 构建

javascript - Node js 中的新日期(年、月、日)自动转换为 UTC 时区

node.js - 使用 jest 测试具有异步函数监听器的 eventEmitter

javascript - 如何在AngularJS中维护404页面的url

javascript - 在我的联系表单中遇到 .fadeOut() .delay() 和 .fadeIn() 问题

javascript - Jquery 中法语编码的问题

javascript - 将 Chrome 扩展程序分解成许多文件会使它变慢吗?

javascript - 从不在 DOM 树中的 jquery 对象复制 Canvas 节点

node.js - 为什么这个 node.js 循环在 112050 次迭代后运行缓慢?

node.js - Node Lambda : Import of ts-node results in TypeError