Last active
February 11, 2019 12:10
-
-
Save Rikezenho/fe2682268fba5e0880c74ee4ccfa48a1 to your computer and use it in GitHub Desktop.
CLI tutorial - step 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const program = require('commander'); | |
const { join } = require('path'); | |
const fs = require('fs'); | |
const inquirer = require('inquirer'); | |
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')); | |
program.version(package.version); | |
program | |
.command('add [todo]') | |
.description('Adiciona um to-do') | |
.action(async (todo) => { | |
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: false | |
}); | |
saveJson(todosPath, data); | |
}); | |
program.parse(process.argv); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment