[英]Passing a JSON from another js file with Express and EJS
I am working on a project to manage printers with CUPS command-line, I have multiple "api's" that make different thinks, for now i just want so see my parsed JSON result in a view, but I'm clueless on how to pass that value trough Express and then render it in a EJS view:我正在开发一个使用 CUPS 命令行管理打印机的项目,我有多个“api”会产生不同的想法,现在我只想看到我解析的 JSON 结果在视图中,但我对如何通过一无所知该值通过 Express,然后在 EJS 视图中呈现:
my api:我的 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);
}
my app.js我的 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')
});
my lpstat.ejs我的 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>
The second parameter in res.render defines the data that is given to your templates: res.render 中的第二个参数定义了提供给模板的数据:
app.get('/lpstat',async (req,res) => {
// Call your api here to fill the variable
const printers = lpstat()
res.render('lpstat', {
printers
})
});
You will be able to use this in your ejs template then然后,您将能够在您的 ejs 模板中使用它
<p>lpstat result:</p>
<%= printers %>
You will need to replace callApi
with whatever function is used to fetch your data.您需要将
callApi
替换为用于获取数据的任何 function。 I used async/await for a simpler answer, can be done with callbacks as well.我使用 async/await 来获得更简单的答案,也可以使用回调来完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.