I got this error when I ran the application below
No existing configuration found. Creating a new one.
/home/lloyd/My_Scripts/directory-mapper/DirectoryMapper.cjs:195
const answers = await inquirer.prompt([
^
TypeError: inquirer.prompt is not a function
at Command.<anonymous> (/home/lloyd/My_Scripts/directory-mapper/DirectoryMapper.cjs:195:38)
Node.js v22.4.0
#!/usr/bin/env node
const fs = require('fs').promises;
const path = require('path');
const { program } = require('commander');
const csv = require('csv-parser');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const inquirer = require('inquirer');
const CONFIG_FILE = 'config.json';
let config = {};
// Load configuration
async function loadConfig() {
try {
const data = await fs.readFile(CONFIG_FILE, 'utf8');
config = JSON.parse(data);
} catch (error) {
console.log('No existing configuration found. Creating a new one.');
config = {};
}
}
// Save configuration
async function saveConfig() {
await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
}
// Traverse directory and extract information
async function traverseDirectory(dir) {
const items = await fs.readdir(dir, { withFileTypes: true });
const results = [];
for (const item of items) {
const itemPath = path.join(dir, item.name);
const itemInfo = {
name: path.parse(item.name).name,
extension: item.isDirectory() ? '' : path.parse(item.name).ext,
path: itemPath,
title: ''
};
results.push(itemInfo);
if (item.isDirectory()) {
results.push(...await traverseDirectory(itemPath));
}
}
return results;
}
// Generate CSV file
async function generateCSV(data, outputPath) {
const csvWriter = createCsvWriter({
path: outputPath,
header: [
{ id: 'name', title: 'Files & Directories' },
{ id: 'extension', title: 'Extension' },
{ id: 'path', title: 'Path' },
{ id: 'title', title: 'Title' }
]
});
await csvWriter.writeRecords(data);
}
// Match titles from dataset
async function matchTitles(data, datasetPath) {
const datasetContent = await fs.readFile(datasetPath, 'utf8');
const dataUnits = datasetContent.split('\n\n');
for (const item of data) {
const matchingUnit = dataUnits.find(unit => {
const nameMatch = unit.match(/Name: (.+)/);
return nameMatch && nameMatch[1] === item.name;
});
if (matchingUnit) {
const titleMatch = matchingUnit.match(/Title: (.+)/);
if (titleMatch) {
item.title = titleMatch[1];
}
}
}
return data;
}
// Generate HTML file
async function generateHTML(data, outputPath) {
let html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Directory Structure</title>
<style>
body { font-family: Arial, sans-serif; }
.folder { cursor: pointer; }
.folder::before { content: '📁 '; }
.file::before { content: '📄 '; }
.info { cursor: help; }
.hidden { display: none; }
.tree-edge { border-left: 1px solid #ccc; padding-left: 10px; }
</style>
</head>
<body>
<h1>Directory Structure</h1>
<div id="tree">
`;
function buildTree(items, level = 0) {
let treeHtml = '';
const indent = ' '.repeat(level);
for (const item of items) {
const isDirectory = !item.extension;
const displayName = item.title || item.name;
const className = isDirectory ? 'folder' : 'file';
const ariaLabel = `${isDirectory ? 'Folder' : 'File'}: ${displayName}`;
treeHtml += `${indent}<div class="${className} tree-edge" aria-label="${ariaLabel}" tabindex="0">\n`;
treeHtml += `${indent} <span class="info" title="${item.path}">ℹ️</span> `;
if (isDirectory) {
treeHtml += `${displayName}\n`;
treeHtml += `${indent} <div class="folder-content hidden">\n`;
treeHtml += buildTree(items.filter(subItem => path.dirname(subItem.path) === item.path), level + 2);
treeHtml += `${indent} </div>\n`;
} else {
treeHtml += `(${item.extension}) ${displayName}\n`;
}
treeHtml += `${indent}</div>\n`;
}
return treeHtml;
}
html += buildTree(data);
html += `
</div>
<script>
document.querySelectorAll('.folder').forEach(folder => {
folder.addEventListener('click', (e) => {
if (e.target.classList.contains('info')) return;
const content = folder.querySelector('.folder-content');
content.classList.toggle('hidden');
});
});
</script>
</body>
</html>
`;
await fs.writeFile(outputPath, html);
}
// Main function
async function main(directory) {
console.log('Scanning directory...');
const data = await traverseDirectory(directory);
console.log('Generating CSV...');
const csvPath = path.join(__dirname, 'output.csv');
await generateCSV(data, csvPath);
if (config.datasetPath) {
console.log('Matching titles from dataset...');
await matchTitles(data, config.datasetPath);
await generateCSV(data, csvPath);
}
console.log('Creating HTML...');
const htmlPath = config.htmlPath || path.join(__dirname, 'output.html');
await generateHTML(data, htmlPath);
console.log(`HTML file generated at: ${htmlPath}`);
}
// CLI setup
program
.version('1.0.0')
.description('Directory structure analyzer')
.argument('<directory>', 'Directory to analyze')
.option('--edit <type>', 'Edit configuration (dataset or html)')
.option('--config', 'Display current configuration')
.action(async (directory, options) => {
await loadConfig();
if (options.edit) {
const answers = await inquirer.prompt([
{
type: 'input',
name: 'path',
message: `Enter the path for ${options.edit}:`,
}
]);
if (options.edit === 'dataset') {
config.datasetPath = answers.path;
} else if (options.edit === 'html') {
config.htmlPath = answers.path;
}
await saveConfig();
console.log('Configuration updated.');
} else if (options.config) {
console.log('Current configuration:');
console.log(config);
} else {
await main(directory);
}
});
program.parse(process.argv);