Skip to content Skip to sidebar Skip to footer

How To Get Input From User Nodejs

I currently have this nodejs code to check if a website server is up or down: var http = require('http'); http.get({host: 'nodejs.org'}, function(res){ if( res.statusCode == 200

Solution 1:

In which environment do you want to use this code? If understand your mean properly, you need to get url from command line as an argument. To do so, take a look at this code:

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!");
   elseconsole.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

I refer you to this post for more information.

Solution 2:

Use readline module. It comes with nodejs.

Example from the 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();
});

Post a Comment for "How To Get Input From User Nodejs"