简体   繁体   English

如何将函数的输出发送到 NodeJS 中的客户端?

[英]How do I send the output of a function to a client in NodeJS?


I am working on a web interface based on NodeJS for my dumb printer. 我正在为我的哑打印机开发基于 NodeJS 的 Web 界面。 In my project, there is a feature which sends all the print jobs which are currently being processed. 在我的项目中,有一个功能可以发送当前正在处理的所有打印作业。 I obtain this information using lpstat (CUPS' status command). 我使用 lpstat(CUPS 的状态命令)获取此信息。 This executes whenever there is a GET request, as you can see here: 每当有 GET 请求时,它就会执行,如下所示:
 const express = require('express'); const { exec } = require('child_process') var currentJobs; function getCurrentJobs() { exec("lpstat", (error, stdout, stderr) => { if (error) { optimisedOutput = "An error occurred : " + `${error}`; } else if (stderr) { optimisedOutput = "An error occurred : " + `${stderr}`; } currentJobs = `${stdout}` console.log(currentJobs) return currentJobs; }) } app.get('/currentJobs', (req, res) => { currentJobs = getCurrentJobs() currentJobs = JSON.stringify(currentJobs) res.status(200).send(currentJobs) console.log(currentJobs); })

But, the variable currentJobs does not update.但是,变量currentJobs不会更新。 Instead, I get an undefined error and Postman does not show any outputs.相反,我收到一个未定义的错误并且 Postman 没有显示任何输出。 It only shows the status code.它只显示状态代码。
Please tell me what I'm doing wrong here.请告诉我我在这里做错了什么。
Edit: This will all be running on a Raspberry Pi 3 connected to the printer which is why I'm using CUPS.编辑:这一切都将在连接到打印机的 Raspberry Pi 3 上运行,这就是我使用 CUPS 的原因。

Your using exec as async execution, you either gonna need to change it to sync(prefer not to, for performance) or wrap it with promise, Ill show you the promise solution.您使用 exec 作为异步执行,您要么需要将其更改为同步(出于性能考虑,最好不要这样做)或用承诺包装它,我将向您展示承诺解决方案。

 const express = require('express'); const { exec } = require('child_process') var currentJobs; async function getCurrentJobs() { return new Promise((resolve) => { exec("lpstat", (error, stdout, stderr) => { if (error) { optimisedOutput = "An error occurred : " + `${error}`; } else if (stderr) { optimisedOutput = "An error occurred : " + `${stderr}`; } currentJobs = `${stdout}` console.log(currentJobs) resolve(currentJobs); }) }) } app.get('/currentJobs', async (req, res) => { currentJobs = await getCurrentJobs() currentJobs = JSON.stringify(currentJobs) res.status(200).send(currentJobs) console.log(currentJobs); })

I think it will be better if you just promisify the function and use it as async/await as it will be much more readable and you are making a asynchronous call and expecting the behaviour of the code in a synchronous manner我认为如果您只是承诺函数并将其用作 async/await 会更好,因为它将更具可读性并且您正在进行异步调用并期望以同步方式的代码行为

const express = require("express");
const { exec } = require("child_process");
const app = express();
app.listen(9999, () => {
  console.log("started");
});
function getCurrentJobs() {
  return new Promise((resolve, rejects) => {
    exec("lpstat", (error, stdout, stderr) => {
      if (error) {
        console.log("An error occurred : " + `${error}`);
        rejects(error);
      } else if (stderr) {
        console.log("An error occurred : " + `${stderr}`);
        rejects(stderr);
      }
      const currentJobs = `${stdout}`;
      console.log(currentJobs);
      resolve(currentJobs);
    });
  });
}

app.get("/currentJobs", async (req, res) => {
  const currentJobs = await getCurrentJobs();
  res.status(200).send(currentJobs);
  console.log(currentJobs);
});

Try using this, it will help you.尝试使用这个,它会帮助你。

You'll have to return a promise otherwise getCurrentJobs() is not returning anything您必须返回一个承诺,否则 getCurrentJobs() 不会返回任何内容

 const express = require("express"); const { exec } = require("child_process"); function getCurrentJobs() { return new Promise((resolve, rejects) => { exec("lpstat", (error, stdout, stderr) => { if (error) { console.log("An error occurred : " + `${error}`); rejects(error); } else if (stderr) { console.log("An error occurred : " + `${stderr}`); rejects(stderr); } const currentJobs = `${stdout}`; console.log(currentJobs); resolve(currentJobs); }); }); } app.get("/currentJobs", async (req, res) => { try { const currentJobs = await getCurrentJobs(); console.log(currentJobs); } catch(err) { res.status(500).send(err); } });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 NodeJS 中运行 function 并向客户端发送响应? - How to run a function in NodeJS and send Response to Client? 如何使用google-api-nodejs-client nodejs在同一线程上发送电子邮件 - How do i send a email on same thread using google-api-nodejs-client nodejs 我如何将与Nodejs MYSQL相关的表分组为JSON并将结果发送到客户端? - how do i group Nodejs MYSQL related tables as JSON and send result to the client? React和NodeJS:如何从服务器向客户端发送数据? - React and NodeJS: How can i send data from server to client? 我不知道如何在 nodejs express 服务器中存储来自 api 调用的 json 数据,并将其发送到反应本机客户端 - I do not know how to store json data from an api call within a nodejs express server, and send it to a react native client 如何在nodejs中输出'i' - How to output 'i' in nodejs 如何在Node.js中正确导出函数? - How do I export a function correctly in nodejs? 如何在Node.js中将整数数组作为字节流写入客户端? - How do I write an array of integers as a bytestream to the client in Nodejs? 如何从nodejs向所有连接的客户端发送变量? - How do I send a variable from nodejs to all the connected clients? 如何通过NodeJS发送带有cookie的HTTP请求? - How do I send HTTP request with cookie by NodeJS?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM