NodeJS 带typescript节点的标准输入问题

hrysbysz  于 2023-08-04  发布在  Node.js
关注(0)|答案(2)|浏览(110)

我需要创建一个脚本,它从标准输入中获取,并等待直到它没有获得用户输入,然后根据用户的操作继续。这是我到目前为止写的代码:

let userInput: string | null = null;
    let standard_in: any = process.stdin;

    standard_in.setRawMode(true);
    standard_in.setEncoding('utf8');
    standard_in.resume();

    process.stdout.write("Welcome to CodeWhisperer code generator\n");
    
    do {
        // some logic to put into a variable some values
        process.stdout.write("This is the command you asked for:\n");
        // display the value
        process.stdout.write("Do you want to use it? (y/n)\n");
        // Get response from the user
        standard_in.on("data", (data: any) => {
            console.log("HERERER")
            userInput = data.toString().trim();
        })

        while (userInput === null) {
            // Wait for user input
        }

        console.log(userInput)
        if (userInput === 'y') {
            process.stdout.write("Great! Let's go!\n");
            interactive = false;
        }
    } while(interactive);

字符串
但如果我这样做,它会永远挂着,什么也不会发生。如果我删除内部的while,代码在没有等待用户输入的情况下结束,我无法读取它。我该如何解决这个问题?

eagi6jfj

eagi6jfj1#

let userInput: string | null = null;
let standard_in: any = process.stdin;

standard_in.setRawMode(true);
standard_in.setEncoding('utf8');
standard_in.resume();

process.stdout.write("Welcome to CodeWhisperer code generator\n");

function getUserInput(): Promise<string> {
    return new Promise((resolve) => {
        standard_in.on("data", (data: any) => {
            userInput = data.toString().trim();
            resolve(userInput);
        });
    });
}

(async () => {
    do {
        // some logic to put into a variable some values
        process.stdout.write("This is the command you asked for:\n");
        // display the value
        process.stdout.write("Do you want to use it? (y/n)\n");

        userInput = await getUserInput();

        console.log(userInput);

        if (userInput === 'y') {
            process.stdout.write("Great! Let's go!\n");
            break;
        }
    } while (true);

    // Add the rest of your code here, if needed
})();

字符串

7hiiyaii

7hiiyaii2#

let userInput: string | null = null;
let standard_in: any = process.stdin;

 standard_in.setRawMode(true);
 standard_in.setEncoding('utf8');
 standard_in.resume();

 process.stdout.write("Welcome to CodeWhisperer code generator\n");

 function processUserInput(data: any) {
   console.log("HERERER");
   userInput = data.toString().trim();

   if (userInput === 'y') {
     process.stdout.write("Great! Let's go!\n");
     standard_in.removeListener("data", processUserInput); // Remove the       
     listener after getting the user input
     // Put any other logic you want to execute after getting 'y' from 
     the user.
         }
      }

     standard_in.on("data", processUserInput);

字符串

相关问题