【问题标题】:Passing a JSON from another js file with Express and EJS使用 Express 和 EJS 从另一个 js 文件传递​​ JSON
【发布时间】:2021-05-16 11:10:46
【问题描述】:

我正在开发一个使用 CUPS 命令行管理打印机的项目,我有多个“api”会产生不同的想法,现在我只想在视图中看到我解析的 JSON 结果,但我一无所知如何通过 Express 传递该值,然后在 EJS 视图中呈现它:

我的 API:

const spawnSync = require("child_process").spawnSync;
const parseStdout = require('../utils/utils.js');

function lpstat(){
let printerList = spawnSync("lpstat -p", {
    timeout: 10000,
    encoding: "utf-8",
  });
 
  let parsedList = parseStdout(printerList);
  
  let onlyPrinterList = parsedList.filter(function (line) {
    return line.match(line.match(/^printer/) || line.match(/^impressora/));
  });
  
  let onlyPrinterNames = onlyPrinterList.map(function (printer) {
    return printer.match(/(?: \S+)/)[0].trim();
  });
  process.on('exit', (code) => {
    process.kill();
  });
  //this is what i want to pass to the view
   return JSON.stringify(onlyPrinterNames);
}

我的 app.js

const express = require('express');
const app = express();

app.listen(3000);
app.set('view engine', 'ejs');


app.get('/lpstat',(req,res) => {
//what should i use here?
    res.render('lpstat')
});

我的 lpstat.ejs

<html lang="en">
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>lpstat</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
    <p>lpstat result:</p>
   <%= what should i use here?%>
</body>
</html>

【问题讨论】:

  • 在技术说明上,您的“API”不是 API,您用来获取数据的 URL 是您的 API(部分)。此外,您从spawn 调用中获取数据的代码是……不寻常的。您是否有理由不使用Nodejs's own documentation 为您提供的示例? (向下滚动到“运行示例ls -lh /usr”)

标签: javascript node.js json express ejs


【解决方案1】:

res.render 中的第二个参数定义了提供给模板的数据:

app.get('/lpstat',async (req,res) => {
    // Call your api here to fill the variable
    const printers = lpstat()
    res.render('lpstat', {
       printers
    })
});

您将能够在您的 ejs 模板中使用它

<p>lpstat result:</p>
<%= printers %>

您需要将callApi 替换为用于获取数据的任何函数。我使用 async/await 来获得更简单的答案,也可以使用回调来完成。

【讨论】:

  • 它会改变我现在使用 spawnSync 的任何东西吗?我不能在同步进程中使用回调,对吗?你能再举一个例子吗?
  • 由于您的函数是同步的,现在您可以删除等待部分。我将为此编辑我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 2022-01-02
  • 2022-01-05
  • 1970-01-01
  • 2018-07-23
  • 2020-12-25
  • 1970-01-01
相关资源
最近更新 更多