別リポの210記事をWordPressに一括移行するNode.jsスクリプト|コピー・投稿の2段階アプローチ
概要
開発リポジトリ(mintor/docs/blog/)に蓄積された210本の開発日記を、articlesリポに移行し、WordPress REST APIで一括投稿するNode.jsスクリプトの設計を解説する。「ファイルコピー」と「WordPress投稿」を分離する2段階アプローチにより、各段階で--dry-run確認が可能な安全な移行を実現する。
課題
- 移行元:
mintor/docs/blog/(メインディレクトリ +note/サブディレクトリ) - 移行先:
articles/mintor/とarticles/note/ - 既に投稿済みの49本(mintor/)と数本(note/)は除外が必要
- 210本を手動コピー・投稿するのは現実的でない
解決策
Step 1: migrate-mintor.js(ファイルコピー)
import { readdirSync, readFileSync, writeFileSync, copyFileSync } from 'fs';
import { join, basename } from 'path';
const SRC_DIR = './mintor/docs/blog';
const DEST_MINTOR = './articles/mintor';
const DEST_NOTE = './articles/note';
const FRONTMATTER = `---
posted_to:
wordpress: null
note: null
mintor: null
---
`;
// 重複チェック: 既存ファイルをSetに格納しO(1)で判定
const existingMintor = new Set(
readdirSync(DEST_MINTOR).filter((f: string) => f.endsWith('.md'))
);
const existingNote = new Set(
readdirSync(DEST_NOTE).filter((f: string) => f.endsWith('.md'))
);
function migrateFile(srcPath: string, destDir: string, existing: Set<string>): void {
const filename = basename(srcPath);
if (existing.has(filename)) {
console.log(`SKIP (duplicate): ${filename}`);
return;
}
const content = readFileSync(srcPath, 'utf-8');
const hasFrontmatter = content.trimStart().startsWith('---');
const newContent = hasFrontmatter ? content : FRONTMATTER + content;
writeFileSync(join(destDir, filename), newContent, 'utf-8');
console.log(`COPY: ${filename} → ${destDir}`);
}
ポイントは以下の通り。
readdirSyncで既存ファイルをSetに格納し、O(1)で重複判定- フロントマターがないファイルには
posted_to:ヘッダーを自動追加 note/サブディレクトリはarticles/note/に振り分け
Step 2: post-migrated.js(WordPress投稿)
// 既に投稿済みのファイルを除外
const originalMintor: string[] = [/* 49件のファイル名 */];
const skipExtra = new Set(['mintor/file1.md', 'note/file2.md', 'note/file3.md']);
const alreadyPosted = new Set<string>();
originalMintor.forEach((f: string) => alreadyPosted.add('mintor/' + f));
function filterNewFiles(files: FileInfo[]): FileInfo[] {
return files.filter((f: FileInfo) => {
const key = f.dir + '/' + f.filename;
return !alreadyPosted.has(key) && !skipExtra.has(key);
});
}
投稿処理は以下のパターンで実行する。
async function postToWordPress(file: FileInfo): Promise<void> {
// 1. Markdown → Gutenbergブロック変換
const content = readFileSync(file.path, 'utf-8');
const gutenbergHtml = markdownToBlocks(content);
// 2. タグ自動検出(最大3つ)
const tags = detectTags(file.title, content);
// 3. JIN:R SEOメタフィールド生成
const seoMeta = generateSeoMeta(file.title, content);
// 4. WordPress API投稿
const payload = {
title: file.title,
content: gutenbergHtml,
status: 'draft',
categories: [detectCategory(file)],
tags,
meta: seoMeta,
};
const result = await wpApiPost('/posts', payload);
// 5. WAFフォールバック
if (!result.success) {
const metaOnly = { title: file.title, status: 'draft', categories: payload.categories, tags, meta: seoMeta };
await wpApiPost('/posts', metaOnly);
}
}
除外リストの管理
ファイル名のプレフィックス(dir/filename)をキーにSetで管理し、誤除外を防ぐ。
// dir/filenameをキーにすることで、異なるディレクトリの同名ファイルを区別
const key = `${file.dir}/${file.filename}`; // e.g. "mintor/2026-01-15-auth-fix.md"
Before/After
| 項目 | Before | After |
|---|---|---|
| 記事の保管場所 | mintor/docs/blog/に散在 | articles/mintor/とarticles/note/に集約 |
| WordPress投稿 | 手動(非現実的) | スクリプトで一括投稿 |
| 重複チェック | 目視 | Set(O(1)判定) |
| フロントマター | ファイルにより有無が不統一 | 全ファイルにposted_to:ヘッダー |
| 移行の安全性 | 一括実行(ロールバック困難) | コピー・投稿分離で各段階--dry-run可能 |
まとめ
大量記事の移行は「コピー」と「投稿」を分離するのが安全である。コピー段階で--dry-runで確認し、投稿段階でも--dry-runで件数を確認してから実行する。除外リストはSetで管理し、dir/filenameをキーにすることで誤除外を防ぐ。210本中208本をコピーし(2本は重複でスキップ)、209本をWordPressに投稿、WAFブロック0件という結果となった。
この記事は、開発の記録をもとに Claude Code が下書きし、私が確認して公開しています。