javascript nunjucks动态更新模版路径 - const app = express()

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力网站平台 👁️ 251 次阅读

每次请求都动态读取文件确实会有一定的性能影响,特别是在高并发的情况下。为了解决这个问题,可以在应用启动时读取模板配置,并在模板更改时更新配置,这样只需要在应用启动和模板更改时读取文件,而不是每次请求都读取文件。

可以使用一个全局变量来缓存当前的模板路径,只有在更改模板时才更新该变量和文件。

以下是改进后的示例代码:

目录结构示例

project

│

├── views/

│ ├── template1/

│ │ └── index.njk

│ ├── template2/

│ │ └── index.njk

│

├── config/

│ └── templateConfig.json

│

├── app.js

templateConfig.json 示例内容

{

"currentTemplate": "template1"

}

app.js 示例代码

const express = require('express');

const nunjucks = require('nunjucks');

const path = require('path');

const fs = require('fs');

const app = express();

// 设置静态文件目录

app.use(express.static(path.join(__dirname, 'public'))); 拼多多帮助力入口

// 全局变量,缓存当前模板路径

let currentTemplatePath;

// 读取配置文件中的当前模板路径

function loadTemplateConfig() {

const config = JSON.parse(fs.readFileSync(path.join(__dirname, 'config/templateConfig.json'), 'utf8'));

currentTemplatePath = config.currentTemplate;

}

// 配置Nunjucks环境

function configureNunjucks() {

nunjucks.configure(path.join(__dirname, `views/${currentTemplatePath}`), {

autoescape: false,

noCache: true,

express: app

});

}

// 初始化时加载配置

loadTemplateConfig();

configureNunjucks();

// 路由

app.get('/', (req, res) => {

res.render('index.njk', { title: 'Hello Nunjucks!' });

});

// 路由:更改模板路径

app.get('/change-template', (req, res) => {

const newTemplate = req.query.template;

if (newTemplate) {

currentTemplatePath = newTemplate;

const config = { currentTemplate: newTemplate };

fs.writeFileSync(path.join(__dirname, 'config/templateConfig.json'), JSON.stringify(config), 'utf8');

configureNunjucks(); // 更新Nunjucks配置

res.send(`Template changed to ${newTemplate}`);

} else {

res.send('No template specified');

}

});

// 启动服务器

const port = 3000;

app.listen(port, () => {

console.log(`服务器已启动,访问地址:http://localhost:${port}`);

});

解释

全局变量 currentTemplatePath:缓存当前的模板路径。loadTemplateConfig 函数:在应用启动时读取模板配置文件,并将路径保存到全局变量中。configureNunjucks 函数:根据缓存的模板路径配置Nunjucks环境。初始化时加载配置:在应用启动时调用 loadTemplateConfig 和 configureNunjucks 函数。更改模板路径的路由:当用户更改模板路径时,更新全局变量、文件并重新配置Nunjucks。

通过这种方式,只有在应用启动和用户更改模板路径时才会读取文件和配置Nunjucks,避免了每次请求都读取文件的性能问题。

参考文章,javascript

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧