我正在运行一个NodeJS脚本,它将生成几个PDF报告。
事情是我需要为每个PDF生成几个图形,所以在几个问题后,我决定生成PNG格式的图形,然后,使html页面包括图像。 从HTML,我生成了一个PDF。
问题是,我实际上并不需要路由,但我需要EJS,并且我需要req/res来生成我的图:
app.get("/operations/:operation/meters/:meter/weekly_report", async (req, res) => { // Used to generate PNG from graph
const meterId = req.params.meter;
const week = req.query.week;
// get meters from meter
const meter = meters.find(it => it.prm === meterId);
const weeklyData = await generateWeeklyGraphForPRM(meter, week);
ejs.renderFile(path.join(__dirname, './views/partials/', "weekly_graph.ejs"), {
days: weeklyData.days,
conso: weeklyData.consoByHour,
meterLabel: meter.label,
}, (err) => {
if (err) {
res.send(err);
} else {
res.render('partials/weekly_graph.ejs', {
days: weeklyData.days,
conso: weeklyData.consoByHour,
meterLabel: meter.label,
});
}
});
后来呢:
async function makePngScreenshot(url, meterId, filename) {
axios.get(url, null); // Make the request to generate html page
const destination = "public/images/" + operation.data.name + "/" + DATE_INI + "_" + DATE_END + "/" + meterId
return new Pageres({delay: 2, filename: filename})
.src(url, ['1300x650'], {crop: true})
.dest(destination)
.run()
}
});
一切正常,但现在,一切都在index.js中
我正在尝试将代码分解成几个文件。
当我将每个路由提取到routes.js中时,我有一个问题,就是我不能再与我的所有endpoint共享任何全局变量。
所以,这里我找到了3个解决方案:
最容易的应该是把路由转换成函数,但是我怎么生成EJS文件,没有路由,有可能吗?
我希望我正确理解你的任务。 我做了一个程序示例,该程序开始使用命令行,接收命令行参数meterid
和week
,从.ejs
模板生成.html
文件。
const path = require('path');
const fs = require('fs');
const argv = require('yargs').argv;
const ejs = require('ejs');
const fsp = fs.promises;
// It would be a good idea to store these parameters in an .env file
const INPUT_FILENAME = 'test.ejs';
const OUTPUT_FILENAME = 'result.html';
const TEMPLATE_FILE = path.resolve(__dirname, './templates', INPUT_FILENAME);
const STORAGE_PATH = path.resolve(__dirname, './storage', OUTPUT_FILENAME);
(async function main({ meterId, week }) {
if (!meterId) {
console.warn('Specify the command line parameter "meterId"!');
process.exit(0);
}
if (!week) {
console.warn('Specify the command line parameter "week"!');
process.exit(0);
}
const html = await ejs.renderFile(TEMPLATE_FILE, { meterId, week }, { async: true });
await fsp.writeFile(STORAGE_PATH, html);
console.log('Done.');
})(argv);
以及运行脚本的示例命令:
node temp.js --meterId=141 --week=44
请让我知道,如果我理解你的任务正确,如果我的例子有助于不知何故。