If you find yourself in a situation where you need to convert a folder structure like this:

  • posts/test/index.md
  • posts/hey-cool-post/index.md

into this:

  • posts/test.md
  • posts/hey-cool-post.md

where the folder containing an index.md file is removed, and the post slug is used as the file name, you can accomplish this using a Node.js script. Below is an example script:

const fs = require('fs');
const glob = require('glob');

const rootFolder = '.'; // search in the current folder

glob(rootFolder + '/**/index.md', (err, files) => {
  if (err) {
    console.log('Error:', err);
  } else {
    for (const filePath of files) {
      const match = filePath.match(/\/(.*?)\//);
      const folderName = match[1];

      fs.copyFile(filePath, `./${folderName}.md`, (err) => {
        if (err) {
          console.log('Error Found:', err);
        } else {
          console.log('File moved!');
        }
      });
    }
  }
});

By running this script, it will recursively search for all index.md files in the specified rootFolder, extract the parent folder name (post slug), and then copy the file to the new location using the post slug as the filename.

Tags: Node.js, file management, folder structure, file conversion