OPのコメントに触発されて、私はOPと同じルートを降りました。
私のサーバーは、オブジェクトの保存後に機能を起動するように設定されています。 (afterSave機能を持つサーバーを解析する)。トリガされた関数は、既存のsitemap.xmlを読み込み、それをjsonに変換し、新しく保存されたオブジェクトのURLをjsonオブジェクトにプッシュし、jsonオブジェクトをxmlに変換して戻し、sitemap.xmlファイル全体を新しいコンテンツ。
この関数は、xml2jsモジュールとNode.js File Systemモジュールを使用します。 ここにその関数の外観を示します。
//load all the required modules first
xml2js = require('xml2js');
var path = require('path');
//parser that does the xml to js conversion
var parser = new xml2js.Parser();
//builder that will reconvert js to xml
var builder = new xml2js.Builder();
//Node.js File System module
const fs = require('fs');
var recentlySavedObject = request.object;
if(recentlySavedObject.get("sitemapUpdated")!==true){
fs.readFile(path.join(__dirname, '../public/sitemap.xml'), function(err, data) {
parser.parseString(data, function (err, result) {
//create a new json object.
var newLoc = {
loc:['<your website url>'+recentlySavedObject.id]
}
//push the newly created object into the url array
result.urlset.url.push(newLoc);
//reconvert js to xml
var xml = builder.buildObject(result);
//try to replace the file with new contents
fs.writeFile(path.join(__dirname, '../public/sitemap.xml'), xml, (err) => {
if (err) throw err;
console.log('It\'s saved!');
//update database entry to prevent this operation from being repeated on consequent updates to this same object
recentlySavedObject.set('sitemapUpdated', true);
promise.push(
recentlySavedObject.save();
return /*when promise resolves*/
});
});
});
}
Todo:オブジェクトがデータベースから削除されたときにサイトマップからエントリを削除します。
私は最初のサイトマップを作ったDIYルートを降りました。新しい投稿が作成されるたびにsitemap.xmlが更新されます。 fsを使用してXMLを読み込み、JSONに変換して簡単に追加してからxmlに戻すことができます。 – userMod2