![](/img/trans.png)
[英]Reusing the already randomly generated number in another JS file - Node.js (ESM not CJS)
[英]How to take user input in Node.js - ESM not CJS
我正在做一個項目,我應該使用 Node.js 創建一個 JavaScript RPG CLI 游戲。我應該使用 ESM 而不是 CommonJS。 執行后,腳本必須顯示 output歡迎,您可以在下方的菜單中選擇開始游戲、加載或退出游戲。 然后,它要求用戶輸入以選擇一個選項。
我已將type: 'module'
放入我的 package.json 以使用 ESM。 我嘗試使用readline和 inquirer.js,但沒有任何效果。 我用npm i inquirer
安裝了 inquirer.js,導入它但它不起作用。 我真的剛剛開始這個項目,我基本上只有幾行代碼。 我不知道問題出在哪里。
這是我嘗試過的代碼之一:
import readline from "readline";
import { stdin as input, stdout as output } from "node:process";
const run = (args) => {
console.clear();
console.log(`
+-----------------------------+
| Welcome ! |
+-----------------------------+
`);
console.log(`
1. Start game 👍
2. Load game 💾
3. Exit ❌
`);
const rl = readline.createInterface({ input, output });
rl.question("Your choice (1-3): ");
rl.close();
};
export default run;
這有幫助嗎?
import readline from "readline";
import { stdin as input, stdout as output } from "node:process";
const run = (args) => {
console.clear();
console.log(`
+-----------------------------+
| Welcome ! |
+-----------------------------+
`);
console.log(`
1. Start game 👍
2. Load game 💾
3. Exit ❌
`);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Your choice (1-3): ", (in)=>{
//your code here
// example:
switch () {
case 1:
start();
break();
case 2:
load();
break();
case 3:
exit();
break();
}
rl.close()
});
};
export default run;
當然,您需要創建start()
、 load()
和exit()
函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.