ca-apm-probe
Version:
CA APM Node.js Agent monitors real-time health and performance of Node.js applications
72 lines (57 loc) • 2.42 kB
JavaScript
// To use CommonJS require, use createRequire:
var fs = require('fs')
var path = require('path')
var fileURLToPath = require('url')
const config = require('ca-apm-probe/lib/configdata').getConfigData();
console.log("APM Probe loaded successfully!");
var indexPath = validateIndexPath();
const snippetFilePath = path.join(__dirname, '../default.snippet');
// Function to append the script to index.html
const appendScriptToHTML = () => {
// Read the content of index.html
fs.readFile(snippetFilePath, 'utf8', (err, snippetContent) => {
if (err) {
console.error('Error reading the .snippet file:', err);
return;
}
fs.readFile(indexPath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading index.html:', err);
return;
}
const isAutoInjectionEnabled = (config.http.browseragent.autoInjectionEnabled == undefined) ? false : config.http.browseragent.autoInjectionEnabled;
const regex = new RegExp(`<head>[\\s\\S]*?<script[^>]*?id="ca_eum_ba"[^>]*>[\\s\\S]*?<\\/script>[\\s\\S]*?<\\/head>`);
if (regex.test(data)) {
const rgx = /<script[^>]*?id="ca_eum_ba"[^>]*>[\s\S]*?<\/script>/i;
data = data.replace(rgx, '');
fs.writeFile(indexPath, data, 'utf8', (err) => {
if (err) {
console.error('Error writing to index.html:', err);
}
});
}
if(isAutoInjectionEnabled){
// Append the script content before the closing </head> tag
const result = data.replace('<head>', `<head>${snippetContent}`);
// Write the modified content back to index.html
fs.writeFile(indexPath, result, 'utf8', (err) => {
if (err) {
console.error('Error writing to index.html:', err);
}
});
}
});
});
};
// Run the function to append the script
appendScriptToHTML();
function validateIndexPath() {
var indexPath='';
const htmlpath = config.react.htmlpath;
if (htmlpath.startsWith('/')) {
indexPath = path.join(__dirname, '../../../' + htmlpath.substring(1));
} else {
indexPath = path.join(__dirname, '../../../' + htmlpath);
}
return indexPath;
}