Skip to content

Instantly share code, notes, and snippets.

@KaeruCT
Created August 7, 2023 13:23
Show Gist options
  • Save KaeruCT/ee37b6ef37195313de7450f1731599b6 to your computer and use it in GitHub Desktop.
Save KaeruCT/ee37b6ef37195313de7450f1731599b6 to your computer and use it in GitHub Desktop.
nodejs script to convert a dokuwiki data folder to markdown files
const fs = require('fs');
const path = require('path');
const folderPath = './'; // Replace with the actual folder path
// Function to rename a file from .txt to .md and replace content
function renameAndReplace(filePath) {
const newFilePath = filePath.replace('.txt', '.md');
fs.renameSync(filePath, newFilePath);
fs.readFile(newFilePath, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading file ${newFilePath}:`, err);
return;
}
let updatedContent = data.replace(/====== (.+) ======/g, '# $1');
updatedContent = updatedContent.replace(/===== (.+) =====/g, '## $1');
updatedContent = updatedContent.replace(/==== (.+) ====/g, '### $1');
updatedContent = updatedContent.replace(/=== (.+) ===/g, '#### $1');
updatedContent = updatedContent.replace(/\[\[(.+?)\|(.+)\]\]/g, (_, p1, p2) => {
return `[[${p1.replace(/:/g, "/")}|${p2}]]`;
});
updatedContent = updatedContent.replace(/\[\[(.+?)\]\]/g, (_, p1,) => {
return `[[${p1.replace(/:/g, "/")}]]`;
});
updatedContent = updatedContent.replace(/\{\{:(.+?)\?(.+?)\|\}\}/g, (_, p1, p2) => {
return `![[${p1.replace(/:/g, "/")}|${p2}]]`;
});
updatedContent = updatedContent.replace(/\{\{:(.+?)\??\}\}/g, (_, p1) => {
return `![[${p1.replace(/:/g, "/")}]]`;
});
updatedContent = updatedContent.replace(/ \*/g, "*");
fs.writeFile(newFilePath, updatedContent, 'utf8', err => {
if (err) {
console.error(`Error writing updated content to ${newFilePath}:`, err);
return;
}
console.log(`File ${newFilePath} has been renamed and content updated.`);
});
});
}
// Function to scan the folder recursively for .txt files and process them
function scanFolderRecursively(folderPath) {
fs.readdir(folderPath, (err, files) => {
if (err) {
console.error(`Error reading folder ${folderPath}:`, err);
return;
}
files.forEach(file => {
const filePath = path.join(folderPath, file);
fs.stat(filePath, (err, stats) => {
if (err) {
console.error(`Error getting stats for ${filePath}:`, err);
return;
}
if (stats.isDirectory()) {
scanFolderRecursively(filePath);
} else if (path.extname(file) === '.txt') {
renameAndReplace(filePath);
}
});
});
});
}
scanFolderRecursively(folderPath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment