|
Line 0
Link Here
|
| 0 |
- |
1 |
const fs = require("fs"); |
|
|
2 |
const path = require("path"); |
| 3 |
const { exec } = require("child_process"); |
| 4 |
const { promisify } = require("util"); |
| 5 |
const execPromise = promisify(exec); |
| 6 |
|
| 7 |
async function modifyXmlElement({ filePath, element, value }) { |
| 8 |
const targetPath = path.resolve(filePath); |
| 9 |
let xmlContent; |
| 10 |
|
| 11 |
try { |
| 12 |
xmlContent = fs.readFileSync(targetPath, "utf8"); |
| 13 |
const regex = new RegExp(`<${element}>[^<]*</${element}>`, "i"); |
| 14 |
const replacement = `<${element}>${value}</${element}>`; |
| 15 |
|
| 16 |
if (!regex.test(xmlContent)) { |
| 17 |
throw new Error(`Element <${element}> not found in ${targetPath}`); |
| 18 |
} |
| 19 |
|
| 20 |
const newContent = xmlContent.replace(regex, replacement); |
| 21 |
fs.writeFileSync(targetPath, newContent, "utf8"); |
| 22 |
|
| 23 |
await execPromise("flush_memcached"); |
| 24 |
await execPromise("koha-plack --restart kohadev"); |
| 25 |
return null; |
| 26 |
} catch (err) { |
| 27 |
return err.message; |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
async function readXmlElementValue({ filePath, element }) { |
| 32 |
const targetPath = path.resolve(filePath); |
| 33 |
let xmlContent; |
| 34 |
|
| 35 |
try { |
| 36 |
xmlContent = fs.readFileSync(targetPath, "utf8"); |
| 37 |
const regex = new RegExp(`<${element}>([^<]*)</${element}>`, "i"); |
| 38 |
const match = xmlContent.match(regex); |
| 39 |
|
| 40 |
if (!match) { |
| 41 |
throw new Error(`Element <${element}> not found in ${targetPath}`); |
| 42 |
} |
| 43 |
|
| 44 |
// Return the value of the element |
| 45 |
return match[1]; // match[1] contains the value between the tags |
| 46 |
} catch (err) { |
| 47 |
return err.message; |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
module.exports = { readXmlElementValue, modifyXmlElement }; |