informasi kontak saya
Surat[email protected]
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Membaca file secara dinamis dengan setiap permintaan memang memiliki dampak kinerja tertentu, terutama dalam situasi konkurensi tinggi. Untuk mengatasi masalah ini, Anda dapat membaca konfigurasi template saat aplikasi dimulai, dan memperbarui konfigurasi saat template berubah, sehingga file hanya perlu dibaca saat aplikasi dimulai dan template berubah, alih-alih membaca file setiap saat. meminta.
Anda dapat menggunakan variabel global untuk menyimpan cache jalur templat saat ini dan hanya memperbarui variabel dan file ketika templat diubah.
Berikut ini contoh kode yang ditingkatkan:
project
│
├── views/
│ ├── template1/
│ │ └── index.njk
│ ├── template2/
│ │ └── index.njk
│
├── config/
│ └── templateConfig.json
│
├── app.js
templateConfig.json
Contoh konten{
"currentTemplate": "template1"
}
app.js
Kode sampelconst 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
: Cache jalur templat saat ini.loadTemplateConfig
fungsi: Membaca file konfigurasi templat saat aplikasi dimulai dan menyimpan jalur ke variabel global.configureNunjucks
fungsi: Konfigurasikan lingkungan Nunjucks berdasarkan jalur templat yang di-cache.loadTemplateConfig
DanconfigureNunjucks
fungsi.Dengan cara ini, file dan konfigurasi Nunjucks hanya dibaca ketika aplikasi dimulai dan pengguna mengubah jalur template, menghindari masalah kinerja dalam membaca file pada setiap permintaan.