Skip to content

Instantly share code, notes, and snippets.

@djibe
Created April 11, 2023 07:24
Show Gist options
  • Save djibe/8179f152f664b8c75e48c0bcd894d550 to your computer and use it in GitHub Desktop.
Save djibe/8179f152f664b8c75e48c0bcd894d550 to your computer and use it in GitHub Desktop.
NodeJS: list files in subfolders with special extension and export a list of renamed files
const fs = require('fs');
const path = require('path');

const directoryPath = path.join(__dirname, './content/recommandations');
const exportPath = path.join(__dirname, './data/application');

// Create the folder directory if it doesn't exist
if (!fs.existsSync(exportPath)) {
  fs.mkdirSync(exportPath);
}

fs.readdir(directoryPath, (err, files) => {
  if (err) {
    return console.log('Unable to scan directory: ' + err);
  }

  const markdownFiles = files.filter((file) => path.extname(file) === '.md');
  const mappedFilenames = markdownFiles.map((file) => `/${path.basename(file, '.md')}/`);

  // console.log('Mapped filenames:', mappedFilenames);

  const arrayAsJs = `{ "mappedFilenames": ${JSON.stringify(mappedFilenames)}}`;

  fs.writeFile(`${exportPath}/mapped-filenames.json`, arrayAsJs, (err) => {
    if (err) {
      console.log('Error saving mapped filenames:', err);
    } else {
      console.log('Mapped filenames saved to mapped-filenames.json');
    }
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment