在快速JS路线中执行子进程

发布于 2025-02-11 21:44:27 字数 558 浏览 0 评论 0原文

我正在尝试在我的快递JS路由中运行一个简单的子进程,并以stdout作为消息值返回JSON消息。 但是由于某种原因,Stdout值不确定任何指针吗?

快速路由代码

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅的被狗咬 2025-02-18 21:44:27

您必须将响应移动到回调中。 cp.exec()是异型的,因此它启动,然后继续执行下一行代码。稍后再调用回调。因此,您需要在回调中发送响应。

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;

而且,此路由处理程序似乎没有任何理由使用asynchandler,因为没有async/等待

而且,您应该正确处理错误。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文