Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

Node.JS Express API Multiline powershell output to HTTP Response res.send

I am new to Node.JS and JavaScript but I am trying to run a PowerShell process initiated by the Node.JS API and return the output of that child process as a Express response.

This is my test.ps1:

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

And this is my Node.JS code:

// 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)})
});

The current output is this:

Line1 Line2 Line3

And I want to have it like this:

Line1
Line2
Line3
question from:https://stackoverflow.com/questions/65945088/node-js-express-api-multiline-powershell-output-to-http-response-res-send

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

if you are trying to look at it in the browser(which is the only place I found it not to work as expected), you could wrap each line in it's own HTML tag. Here is what I did to achieve the expected result when looking at the result in 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("
");
      // 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);
    }
  );
});

Hope this solves your problem :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...