Home > Net >  Executing child process in express js route
Executing child process in express js route

Time:07-01

I am trying to run a simple child process in my express js route and return a json message with the stdout as the message value. But for some reason the stdout value is undefined any pointers?

express route code

const express = require("express")
const asyncHandler = require("express-async-handler")
const cp = require('child_process')
const router =  express.Router()

router.get("/status", asyncHandler( async (req, res) => {
    
    let msg 

    cp.exec('ls', (err, stdout, stderr) => {
        console.log('#1, exec')
        console.log(stdout)
        msg = stdout
    })

    res.json({message:`${msg}`})
}))

module.exports = router

CodePudding user response:

You have to move the response INSIDE the callback. cp.exec() is asycnhronous so it starts up and then continues executing the next lines of code. The callback is called sometime later. So, you need to send your response INSIDE the callback.

const express = require("express")
const cp = require('child_process')
const router =  express.Router()

router.get("/status", (req, res) => {
    
    cp.exec('ls', (err, stdout, stderr) => {
        if (err) {
             console.log(err);
             res.sendStatus(500);
             return;
        }
        console.log('#1, exec');
        console.log(stdout);
        res.json({message:`${stdout}`});
    })
});


module.exports = router;

And, this route handler doesn't seem to have any reason to use asyncHandler as there's no async/await in use.

And, you should properly handle errors.

  • Related