【问题标题】:Node.JS Express API Multiline powershell output to HTTP Response res.sendNode.JS Express API Multiline powershell 输出到 HTTP 响应 res.send
【发布时间】:2021-05-02 19:39:17
【问题描述】:

我是 Node.JS 和 JavaScript 的新手,但我正在尝试运行由 Node.JS API 启动的 PowerShell 进程,并将该子进程的输出作为 Express 响应返回。

这是我的 test.ps1:

write-host "Line1"
Write-Host "Line2"
Write-Host "Line3"

这是我的 Node.JS 代码:

// test
// http://localhost:4420/test
Router.get('/test', function(req, res) {
        const { exec } = require('child_process');
        exec(`.\\server\\scripts\\test.ps1`, {'shell':'powershell.exe'}, (error, stdout, stderr)=> {res.send(stdout)})
});

当前的输出是这样的:

Line1 Line2 Line3

我想要这样:

Line1
Line2
Line3

【问题讨论】:

    标签: node.js powershell api rest express


    【解决方案1】:

    如果您尝试在浏览器中查看它(这是我发现它无法按预期工作的唯一地方),您可以将每一行包装在它自己的 HTML 标记中。这是我在 Chrome 中查看结果时为达到预期结果所做的。

    router.get("/", (req, res, next) => {
      const { exec } = require("child_process");
      exec(
        `.\\server\\scripts\\test.ps1`,
        { shell: "powershell.exe" },
        (error, stdout, stderr) => {
          // Split each line by the new line character, 
          // results in [ 'Line 1', 'Line 2', 'Line 3', '' ]
          const splitLines = stdout.split("\n");
          // deletes last element in array, which is blank
          splitLines.pop();
          // use .map function to add HTML tag wrapper around each element in array
          // use .join("") to transform array back to a single string
          const convertToHTML = splitLines.map(line => {
            return `<div>${line}<div>`
          }).join("")
          // now express serves up the string as HTML, so now the result is in multiple lines
          res.send(convertToHTML);
        }
      );
    });
    

    希望这能解决你的问题:)

    【讨论】:

    • 谢谢!这确实在浏览器中起到了作用。就像你说的,在我实际上想使用结果的应用程序中,它的格式已经正确。愚蠢的我,我没有先检查,我认为结果与我的网络浏览器中的结果相同。今天学到东西了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-11-12
    • 2022-06-16
    • 1970-01-01
    • 2013-12-02
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多