0

I am trying to run an async/await operation to create a new record of a model named Log. I carried out this operation within my child process exec function, but for some reason, the operation does not work since the await operation triggers a syntax error yet it is within an async function.

My child process exec function runs within an async function acting as my handler for an express JS route

const express = require("express")
const router =  express.Router()
const cp = require('child_process')
const Log = require('../models/logModel')



router.get("/status", asyncHandler( async (req, res) => {
    
    const cmd = 'pwd'

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

        const newLog = await Log.create({
            cmd: cmd,
            output: `${stdout}`
        })

        res.status(200).json({log: newLog})
    })
}) )


module.exports = router
Jordan Rob
  • 322
  • 2
  • 16
  • FWIW, instead of running `pwd` you can also use `process.cwd()` – robertklep Jul 02 '22 at 09:08
  • 1
    The callback to `cp.exec()` is the "closest" function to your `await`, so that should be `async`. – robertklep Jul 02 '22 at 09:25
  • @robertklep thanks this works I added the async keyword to the callback function within `cp.exec() ` but I was wondering why this is the case yet according to child process docs child process functions such as `exec() ` are async by default. – Jordan Rob Jul 02 '22 at 09:42
  • 2
    They are _asynchronous_, which is something different from "being marked with `async`". But regardless, the closest function to an `await` needs to be marked `async`. – robertklep Jul 02 '22 at 10:20

0 Answers0