1

I have simple express web server and a function that execute docker ps. How i can print result of a function into my browser?

const { exec } = require("child_process");
const express = require('express')
const app = express()
function docker() {

    exec("docker ps", (error, stdout, stderr) => {
        if (error) {
            console.log(`error: ${error.message}`);
            return;
        }
        if (stderr) {
            console.log(`stderr: ${stderr}`);
            return;
        }
        console.log( `${stdout}`);
    })

}
docker();

app.get('/', function (req, res) {
    res.send(`${docker()}`)
})

app.listen(3000)
kumite
  • 47
  • 4

1 Answers1

0

You could pass a callback into docker() (functions should be verbs/actions, not nouns, so I'd rename this to runDocker) and call your res.send() function there, but it's much cleaner to promisify the exec callback using the util module:

const express = require("express");
const {promisify} = require("util");
const exec = promisify(require("child_process").exec);

const runDocker = async () => {
  const {stdout, stderr} = await exec("docker ps");

  if (stderr) {
    throw Error(stderr);
  }

  return stdout;
};

express()
  .get("/", async (req, res) => {
    try {
      res.send(await runDocker());
    }
    catch (err) {
      console.error(err);
      res.sendStatus(500);
    }
  })
  .listen(3000)
;

Typically, logging should happen in the calling scope, not a side effect in a function. You can add a general async error handler for multiple routes.

ggorlen
  • 44,755
  • 7
  • 76
  • 106