是否可以在没有路由的情况下使用 EJS 和 nodeJS/Express

Is it possible to use EJS without routes with nodeJS / Express

我是 运行 将生成多个 PDF 报告的 NodeJS 脚本。

问题是我需要为每个 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 时,我遇到了无法与所有端点共享任何全局变量的问题。

所以,我在这里找到了 3 个解决方案:

最简单的方法应该是将路由转换为函数,但是如何生成没有路由的 EJS 文件,这可能吗?

希望我正确理解了您的任务。我做了一个程序的例子,它开始使用命令行,接收命令行参数 meterIdweek,从 .ejs 模板生成一个 .html 文件。我还使用了 yargs 包来轻松解析命令行参数。

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) {
        return console.warn('Specify the command line parameter "meterId"!');
    }
    
    if (!week) {
        return console.warn('Specify the command line parameter "week"!');
    }

    try {
        const html = await ejs.renderFile(TEMPLATE_FILE, { meterId, week }, { async: true });
        await fsp.writeFile(STORAGE_PATH, html);
        console.log('Done.');
    } catch (error) {
        console.error(error);
        process.exit(1);
    }
})(argv);

以及 运行 脚本的示例命令:

node script.js --meterId=141 --week=44

请告诉我我是否正确理解了您的任务,以及我的示例是否对您有所帮助。