[英]Run JavaScript codes in Visual Studio code terminal same as what works in browser's console
這是一個基本的 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 代碼在瀏覽器之外運行,所以你會看到 vanilla 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); });
使用 node 命令運行上面的代碼
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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.