Newer
Older
hello-programmer-world / src / plugins / remarkCodeFile.ts
@h.sakamoto h.sakamoto on 16 Dec 720 bytes commit
import fs from "node:fs";
import path from "node:path";
import { visit } from "unist-util-visit";

export default function remarkCodeFile() {
	return (tree: any, file: any) => {
		visit(tree, "code", (node) => {
			console.log("Processing code node with meta:", node.meta);

			if (!node.meta) return;

			const match = node.meta.match(/file=(.+)/);
			if (!match) return;

			const relativePath = match[1].trim();
			const fullPath = path.resolve(process.cwd(), relativePath);

			if (!fs.existsSync(fullPath)) {
				node.value = `Error: File not found - ${relativePath}`;
				return;
			}

			node.value = fs.readFileSync(fullPath, "utf8");
			node.meta = undefined; // meta は消しておく(任意)
		});
	};
}