Skip to content

Instantly share code, notes, and snippets.

@Rikezenho
Last active February 11, 2019 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rikezenho/74ac4bda7d85693fcb5b2f96cfd04ced to your computer and use it in GitHub Desktop.
Save Rikezenho/74ac4bda7d85693fcb5b2f96cfd04ced to your computer and use it in GitHub Desktop.
CLI tutorial - step 7
#!/usr/bin/env node
const program = require('commander');
const { join } = require('path');
const fs = require('fs');
const inquirer = require('inquirer');
const chalk = require('chalk');
const Table = require('cli-table');
const package = require('./package.json');
const todosPath = join(__dirname, 'todos.json');
const getJson = (path) => {
const data = fs.existsSync(path) ? fs.readFileSync(path) : [];
try {
return JSON.parse(data);
} catch (e) {
return [];
}
};
const saveJson = (path, data) => fs.writeFileSync(path, JSON.stringify(data, null, '\t'));
const showTodoTable = (data) => {
const table = new Table({
head: ['id', 'to-do', 'status'],
colWidths: [10, 20, 10]
});
data.map((todo, index) =>
table.push(
[index, todo.title, todo.done ? chalk.green('feito') : 'pendente']
)
);
console.log(table.toString());
}
program.version(package.version);
program
.command('add [todo]')
.description('Adiciona um to-do')
.option('-s, --status [status]', 'Status inicial do to-do')
.action(async (todo, options) => {
let answers;
if (!todo) {
answers = await inquirer.prompt([
{
type: 'input',
name: 'todo',
message: 'Qual é o seu to-do?',
validate: value => value ? true : 'Não é permitido um to-do vazio'
}
]);
}
const data = getJson(todosPath);
data.push({
title: todo || answers.todo,
done: (options.status === 'true') || false
});
saveJson(todosPath, data);
console.log(`${chalk.green('To-do adicionado com sucesso!')}`);
});
program
.command('list')
.description('Lista os to-dos')
.action(() => {
const data = getJson(todosPath);
showTodoTable(data);
});
program.parse(process.argv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment