【发布时间】: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