Skip to content

Instantly share code, notes, and snippets.

@lot224
Created November 1, 2019 15:32
Show Gist options
  • Save lot224/decac0b4790b5e03b587e411abe8aae1 to your computer and use it in GitHub Desktop.
Save lot224/decac0b4790b5e03b587e411abe8aae1 to your computer and use it in GitHub Desktop.
nodejs simple file menu
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const cwd = process.cwd();
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const files = [];
const filterExtension = null; // ".json"
fs.readdirSync(cwd).forEach(file => {
if (!filterExtension || file.endsWith(filterExtension)) {
files.push(file);
}
});
const killWords = ['quit', 'q', 'exit'];
let fn = {
"showList": () => {
let question = `Please select a number? 1-${files.length}\n\n`;
for (let i = 0; i < files.length; i++) {
question += `[${i + 1}] ${files[i]}\n`
}
question += '\n> ';
fn.getFile(question);
},
"getFile": (question) => {
rl.question(question, (input) => {
input = input.toLowerCase();
if (isNaN(input)) {
if (killWords.indexOf(input) != -1) {
console.log('bye.');
rl.close();
} else if (input === 'list') {
fn.showList();
} else if (input === 'help') {
fn.showList();
} else {
fn.getFile(`Please enter a number (1 - ${files.length}) > `);
}
} else {
let index = Number(input);
if (input > 0 && input < files.length + 1) {
fn.action(files[index - 1]);
rl.close();
} else {
fn.getFile(`Invalid number, please enter a number (1 - ${files.length}) > `);
}
}
})
},
"action": (file) => {
file = path.join(cwd, file);
console.log(`Action on "${file}"`);
}
}
if (files.length === 0) {
if (filterExtension) {
console.log(`No ${filterExtension.replace('.', '')} files present in directory. Copy the ${filterExtension.replace('.', '')} file('s) into \n'${cwd}'`);
}
rl.close();
} else {
if (files.length > 1) {
fn.showList();
}
else {
// we don't need to ask any questions so, kill the readline tool.
rl.close();
fn.action(files[0]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment