Global configuration properties and utility functions for customizing EJS behavior.
EJS provides a caching system for compiled template functions to improve performance.
/**
* EJS template function cache object
* Implements Cache interface with get, set, remove, reset methods
*/
const cache = {
/** Get cached template function by key */
get(key: string): Function | undefined;
/** Cache template function with key */
set(key: string, value: Function): void;
/** Remove cached template function */
remove(key: string): void;
/** Clear all cached templates */
reset(): void;
};
/**
* Clear intermediate JavaScript cache
* Calls cache.reset() to remove all cached templates
*/
function clearCache(): void;Usage Examples:
const ejs = require("ejs");
// Cache is used automatically when filename is provided
ejs.renderFile("template.ejs", data, { cache: true });
// Manually manage cache
console.log(ejs.cache.get("template.ejs")); // undefined initially
// After rendering with cache enabled
ejs.renderFile("template.ejs", data, { cache: true });
console.log(typeof ejs.cache.get("template.ejs")); // 'function'
// Clear all cached templates
ejs.clearCache();
// Replace default cache with LRU cache
const LRU = require("lru-cache");
ejs.cache = new LRU({ max: 100 });Customize how EJS loads template files with the fileLoader property.
/**
* Custom file loader function for template preprocessing or access control
* @param filePath - Path to template file
* @returns Template file contents as string
*/
let fileLoader: (filePath: string) => string;Usage Examples:
const ejs = require("ejs");
const fs = require("fs");
// Default file loader
console.log(ejs.fileLoader === fs.readFileSync); // true
// Custom file loader with preprocessing
ejs.fileLoader = (filePath) => {
const content = fs.readFileSync(filePath, 'utf8');
// Preprocess template (e.g., remove comments)
return content.replace(/<%#[\s\S]*?%>/g, '');
};
// Custom file loader with access control
ejs.fileLoader = (filePath) => {
// Only allow files in specific directory
if (!filePath.startsWith('/safe/templates/')) {
throw new Error('Access denied');
}
return fs.readFileSync(filePath, 'utf8');
};
// Custom file loader with remote templates
ejs.fileLoader = async (filePath) => {
if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
const response = await fetch(filePath);
return await response.text();
}
return fs.readFileSync(filePath, 'utf8');
};Configure global EJS settings that apply to all templates.
/**
* Name of the object containing locals in templates
* Default: 'locals'
*/
let localsName: string;
/**
* Promise implementation for async operations
* Default: native Promise if available
*/
let promiseImpl: PromiseConstructorLike;Usage Examples:
const ejs = require("ejs");
// Change locals name globally
ejs.localsName = 'data';
// Templates will use 'data' instead of 'locals' as variable name
// Use custom Promise implementation
ejs.promiseImpl = require('bluebird');Utility functions for include resolution and output escaping.
/**
* Get the path to included file from parent file path and specified path
* @param name - Specified include path
* @param filename - Parent file path
* @param isDir - Whether parent file path is a directory (default: false)
* @returns Resolved include path
*/
function resolveInclude(name: string, filename: string, isDir?: boolean): string;
/**
* Escape characters reserved in XML/HTML
* @param markup - Input string to escape
* @returns Escaped string with HTML entities
*/
function escapeXML(markup: string): string;Usage Examples:
const ejs = require("ejs");
// Resolve include paths
const includePath = ejs.resolveInclude("header.ejs", "/views/main.ejs");
console.log(includePath); // "/views/header.ejs"
const includePath2 = ejs.resolveInclude("header", "/views/", true);
console.log(includePath2); // "/views/header.ejs"
// Escape HTML content
const escaped = ejs.escapeXML('<script>alert("xss")</script>');
console.log(escaped); // "<script>alert("xss")</script>"
// Use in custom escape function
const customOptions = {
escapeFunction: (str) => {
// Custom escaping logic
return ejs.escapeXML(str).replace(/'/g, ''');
}
};Access EJS version and metadata information.
/**
* EJS version string
* @readonly
*/
const VERSION: string;
/**
* Package name for detection
* @readonly
*/
const name: string;Usage Examples:
const ejs = require("ejs");
console.log(ejs.VERSION); // "3.1.10"
console.log(ejs.name); // "ejs"
// Version checking
const [major, minor, patch] = ejs.VERSION.split('.').map(Number);
if (major >= 3) {
// Use features available in v3+
}EJS provides seamless Express.js integration through a view engine alias.
/**
* Express.js view engine support
* Alias for renderFile function to support Express.js out-of-the-box
*/
const __express = renderFile;Usage Examples:
const express = require("express");
const ejs = require("ejs");
const app = express();
// Set EJS as view engine
app.set("view engine", "ejs");
// Express automatically uses ejs.__express (which is ejs.renderFile)
app.get("/", (req, res) => {
res.render("index", { title: "My App" });
});
// Manual usage of __express
ejs.__express("template.ejs", { data: "value" }, (err, html) => {
if (err) throw err;
console.log(html);
});Configure EJS for specific environments and use cases.
const ejs = require("ejs");
// Production configuration
if (process.env.NODE_ENV === 'production') {
// Enable caching for all renders
ejs.cache = new Map(); // Or use LRU cache
// Disable debug features
const originalRender = ejs.render;
ejs.render = (template, data, opts = {}) => {
return originalRender(template, data, {
...opts,
debug: false,
compileDebug: false
});
};
}
// Development configuration
if (process.env.NODE_ENV === 'development') {
// Clear cache on file changes
const fs = require("fs");
const chokidar = require("chokidar");
chokidar.watch("./views/**/*.ejs").on("change", () => {
ejs.clearCache();
});
}