问题描述
这是一个基本的vs代码问题,但是我对这个代码编辑器有些陌生。我需要在vs代码平台中运行/ console.log()
一个简单的js脚本,与在浏览器控制台或此“代码段”中运行的脚本相同。仅以我的简单js脚本为例:
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);
如果我在浏览器中console.log()
,它看起来像这样。弹出提示,您可以输入值并在日志上查看结果。
如何在Vs代码终端中执行此操作,而不是转到浏览器的控制台,运行并查看结果?我尝试在vs代码终端中运行node test.js
例如。当然,由于没有定义prompt
,所以会出现错误。我已经看过并尝试过浏览器预览扩展,但是不适用于像这样的简单代码。设置的json脚本或任何有效的扩展名?感谢您的帮助。
解决方法
我们知道node.js代码在浏览器外部运行,因此您会发现香草JavaScript和nodeJs略有不同。
在nodeJS中接受用户输入时,您需要像在C ++或JAVA代码中那样从终端读取行
示例
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);
});
使用节点命令运行以上代码
,Vanilla JavaScript和Node.js有一些区别,这就是其中之一。您有一些选择:
- 您可以使用内置的
readline
模块
const 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);
});
参考:https://nodejs.org/en/knowledge/command-line/how-to-prompt-for-command-line-input/
- 您可以使用软件包管理器进行安装,然后使用第三方库。此类库的一个示例是
prompt
。有些人使用这些第三方库是因为它们有助于验证用户输入。
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);
});