Add or replace 'Sitemap: ...'
This commit is contained in:
@ -1,5 +1,5 @@
|
|||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import os from "node:os";
|
import os from 'node:os';
|
||||||
|
|
||||||
const tasksIntegration = () => {
|
const tasksIntegration = () => {
|
||||||
let config;
|
let config;
|
||||||
@ -9,14 +9,13 @@ const tasksIntegration = () => {
|
|||||||
hooks: {
|
hooks: {
|
||||||
'astro:config:done': async ({ config: cfg }) => {
|
'astro:config:done': async ({ config: cfg }) => {
|
||||||
config = cfg;
|
config = cfg;
|
||||||
console.log(config);
|
|
||||||
},
|
},
|
||||||
|
|
||||||
'astro:build:done': async () => {
|
'astro:build:done': async () => {
|
||||||
try {
|
try {
|
||||||
const outDir = config.outDir;
|
const outDir = config.outDir;
|
||||||
const publicDir = config.publicDir;
|
const publicDir = config.publicDir;
|
||||||
const sitemapName = "sitemap-index.xml";
|
const sitemapName = 'sitemap-index.xml';
|
||||||
const sitemapFile = new URL(sitemapName, outDir);
|
const sitemapFile = new URL(sitemapName, outDir);
|
||||||
const robotsTxtFile = new URL('robots.txt', publicDir);
|
const robotsTxtFile = new URL('robots.txt', publicDir);
|
||||||
const robotsTxtFileInOut = new URL('robots.txt', outDir);
|
const robotsTxtFileInOut = new URL('robots.txt', outDir);
|
||||||
@ -28,14 +27,24 @@ const tasksIntegration = () => {
|
|||||||
|
|
||||||
if (hasIntegration && sitemapExists) {
|
if (hasIntegration && sitemapExists) {
|
||||||
const robotsTxt = fs.readFileSync(robotsTxtFile, { encoding: 'utf8', flags: 'a+' });
|
const robotsTxt = fs.readFileSync(robotsTxtFile, { encoding: 'utf8', flags: 'a+' });
|
||||||
|
const sitemapUrl = new URL(sitemapName, String(new URL(config.base, config.site)));
|
||||||
|
const pattern = /^Sitemap:(.*)$/m;
|
||||||
|
|
||||||
if (!robotsTxt.includes("Sitemap:")) {
|
if (!pattern.test(robotsTxt)) {
|
||||||
const sitemapUrl = new URL(sitemapName, String(new URL(config.base, config.site)));
|
fs.appendFileSync(robotsTxtFileInOut, `${os.EOL}${os.EOL}Sitemap: ${sitemapUrl}`, {
|
||||||
const content = `${os.EOL}${os.EOL}Sitemap: ${sitemapUrl}`
|
encoding: 'utf8',
|
||||||
fs.appendFileSync(robotsTxtFileInOut, content, { encoding: 'utf8', flags: 'w' })
|
flags: 'w',
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
fs.writeFileSync(robotsTxtFileInOut, robotsTxt.replace(pattern, `Sitemap: ${sitemapUrl}`), {
|
||||||
|
encoding: 'utf8',
|
||||||
|
flags: 'w',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) { /* empty */ }
|
} catch (err) {
|
||||||
|
/* empty */
|
||||||
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
Reference in New Issue
Block a user