在快速JS路线中执行子进程
我正在尝试在我的快递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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须将响应移动到回调中。
cp.exec()
是异型的,因此它启动,然后继续执行下一行代码。稍后再调用回调。因此,您需要在回调中发送响应。而且,此路由处理程序似乎没有任何理由使用
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.And, this route handler doesn't seem to have any reason to use
asyncHandler
as there's noasync/await
in use.And, you should properly handle errors.