如何获得正确的 NodeJS Child Process.spawn 输出

How To Get The Correct NodeJS Child Process.spawn Output

我正在尝试通过 child_process 模块从 NodeJS 运行 ls -la。但是,当我 运行 它时,它可以工作,但它没有给我正确的输出。相反,我得到这个:

我希望结果看起来更像这样:

这是我的代码:

const child_process = require("child_process")


function runShell(command) {
    let shellCommand = command.split(" ")[0]
    let commandArgs = command.split(" ").slice(1, command.length)
    let script = child_process.spawn(shellCommand, commandArgs)
    
    script.stdout.on("data", (data) => {
        console.log(data)
    })

    script.stderr.on("data", (data) => {
        console.warn(`Error: ${data}`)
    })

    script.on("close", (code) => {
        console.log(`Script Ended On code ${code}`)
    })
}
runShell("ls -la")

我做错了什么?我该如何解决?

我明白了。所以你需要做的是出于某种原因,console.log 对于 stdout 数据不起作用,除非你把它放在一个字符串中。 新代码将是:

const child_process = require("child_process")


function runShell(command) {

    let shellCommand = command.split(" ")[0]
    let commandArgs = command.split(" ").slice(1, command.length)
    let script = child_process.spawn(shellCommand, commandArgs)
    
    script.stdout.on("data", (data) => {
        console.log(`${data}`) # This has been changed
    })

    script.stderr.on("data", (data) => {
        console.warn(`Error: ${data}`)
    })

    script.on("close", (code) => {
        console.log(`Script Ended On code ${code}`)
    })
}
runShell("ls -la")

我不是 100% 确定为什么要打印正确的输出需要发生这种情况。

编辑:

更好的解决方案是让 nodejs 处理所有标准 IO。 新代码将是:

function runShell(command){
    let shellCommand = command.split(" ")[0]
    let commandArgs = command.split(" ")
    commandArgs.shift()

    const executeCommand = spawn(shellCommand, commandArgs, {
        stdio: [process.stdin, process.stdout, process.stderr]
    })
}