Skip to content

Instantly share code, notes, and snippets.

@wajeht
Created February 16, 2024 16:05
Show Gist options
  • Save wajeht/f7378d6ef85641e9a806aa08072d3ece to your computer and use it in GitHub Desktop.
Save wajeht/f7378d6ef85641e9a806aa08072d3ece to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
if (process.argv.length <= 4) {
console.log('Usage: node index.js <input_directory> <source_file_extension> <output_directory> <output_file_extension>');
process.exit(1);
}
const directoryPath = process.argv[2];
const sourceExtension = process.argv[3];
const outputDirectory = process.argv[4];
const outputExtension = process.argv[5];
const validExtensions = ['md', 'txt'];
if (!validExtensions.includes(sourceExtension) || !validExtensions.includes(outputExtension)) {
console.error('Error: Invalid file extension. Valid extensions are:', validExtensions.join(', '));
process.exit(1);
}
if (!fs.existsSync(directoryPath)) {
console.error('Error: Input directory does not exist:', directoryPath);
process.exit(1);
}
if (!fs.existsSync(outputDirectory)) {
console.error('Error: Output directory does not exist:', outputDirectory);
process.exit(1);
}
const currentDate = new Date();
const formattedDate = `${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${currentDate.getDate().toString().padStart(2, '0')}-${currentDate.getFullYear()}-${currentDate.getHours().toString().padStart(2, '0')}-${currentDate.getMinutes().toString().padStart(2, '0')}-${currentDate.getSeconds().toString().padStart(2, '0')}-${currentDate.getHours() >= 12 ? 'pm' : 'am'}`;
const outputFilePath = path.join(outputDirectory, `${formattedDate}-combined.${outputExtension}`);
const getAllFiles = (dirPath, arrayOfFiles, extension) => {
let files = fs.readdirSync(dirPath);
arrayOfFiles = arrayOfFiles || [];
files.forEach(file => {
if (fs.statSync(path.join(dirPath, file)).isDirectory()) {
arrayOfFiles = getAllFiles(path.join(dirPath, file), arrayOfFiles, extension);
} else {
if (file.endsWith('.' + extension)) {
arrayOfFiles.push(path.join(dirPath, file));
}
}
});
return arrayOfFiles;
}
let files = getAllFiles(directoryPath, [], sourceExtension);
let content = '';
files.forEach(filePath => {
content += fs.readFileSync(filePath, 'utf8') + '\n';
});
fs.writeFileSync(outputFilePath, content);
console.log(`All .${sourceExtension} files have been combined into ${outputFilePath}`);
@wajeht
Copy link
Author

wajeht commented Feb 16, 2024

$ node combine.js ~/Dev/filament md ~/Desktop/ txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment