This is a basic vs code question, but I'm kinda new to this code editor. I need to run/ console.log()
a simple js script in vs code platform same as what works in the browser's console or this "code snippet". Just for example of my simple js script:
const data = parseInt(prompt("5 x 5?")); const testResult = (answer) => data === answer ? console.log(`Correct. Your answer was: ${data}`) : console.log(`Incorrect. Your answer was: ${data}. Pls try again`) testResult(25);
If I console.log()
this in the browser, it looks something like this. A prompts pops up and you can enter the value and see the result on the log.
How do I do this in Vs code terminal instead of going to a browser's console, run and see the result? I tried to run it for example node test.js
in vs code terminal. Of course, it's getting an error, because prompt
is not defined. I've seen and tried browser preview extension, but doesn't work for a simple code like this. A json script for a setting maybe or any extension that works? Thanks for your help.
As we know node.js code run outside of browser so you will see slightly difference between vanilla JavaScript and nodeJs.
In nodeJS for taking input from users you need to readline from terminal as we do in C++ or JAVA code
Example
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("What is your name ? ", function(name) { rl.question("Where do you live ? ", function(country) { console.log(`${name}, is a citizen of ${country}`); rl.close(); }); }); rl.on("close", function() { console.log("\\nBYE BYE !!!"); process.exit(0); });
run above code using node command
Vanilla JavaScript and Node.js have some differences and this is one of them. You have some options:
readline
moduleconst readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("How old are you ? ", function(age) {
console.log(`You are ${age} years old`);
rl.close();
});
});
rl.on("close", function() {
process.exit(0);
});
Reference: https://nodejs.org/en/knowledge/command-line/how-to-prompt-for-command-line-input/
prompt
. Some people use these third-party libraries because they help to validate the user input.var prompt = require('prompt');
//
// Start the prompt
//
prompt.start();
//
// Get two properties from the user: username and email
//
prompt.get(['username', 'email'], function (err, result) {
//
// Log the results.
//
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
});
Reference: https://github.com/flatiron/prompt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.