【问题标题】:How to display prompts and command outputs simultaneously in Nodejs?如何在Nodejs中同时显示提示和命令输出?
【发布时间】:2022-12-04 11:51:18
【问题描述】:

I am trying to make a shell environment using Nodejs and encountered the following flaw in my program. I tried using the readline-sync and prompt-sync for resolving the issue and described about the problem next.

I am having the below code:

const prompt = require(\'prompt-sync\')({sigint: true});
const { spawn } = require(\"child_process\");
const os = require(\'os\')
working_dir = os.homedir();

user_cmd = \"\";

while (user_cmd != \"exit\") {
    user_cmd = prompt(working_dir + \" >\");
    
    if (user_cmd.match(\"ls\") != null) {
        const ls = spawn(\"ls\");
        
        ls.stdout.on(\"data\", data => {
            console.log(`${data}`);
        });

        ls.stderr.on(\"data\", data => {
            console.log(`${data}`);
        });

        ls.on(\'error\', (error) => {
            console.log(`${error.message}`);
        });
    }
} 

I want output in this way:

OUTPUT AFTER EACH PROMPT

hi@SanthoshSingh:/mnt/e/Atri Labs$ node shell.js 
/home/hi >ls
hi.js
ls.js
node_modules
package-lock.json
package.json
shell.js
/home/hi >exit

but getting the output in this way:

AFTER ALL PROMPTS GETTING THE OUTPUT

hi@SanthoshSingh:/mnt/e/Atri Labs$ node shell.js 
/home/hi >ls
/home/hi >exit
hi.js
ls.js
node_modules
package-lock.json
package.json
shell.js

Get me a solution people :-)

    标签: node.js process readline-sync


    【解决方案1】:
    猜你喜欢
    • 2012-08-08
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2014-10-12
    • 2014-04-16
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多