Skip to content

Instantly share code, notes, and snippets.

@Rikezenho
Last active February 11, 2019 12:11
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/f2b0744a85457b54e14195ab9a637a8f to your computer and use it in GitHub Desktop.
Save Rikezenho/f2b0744a85457b54e14195ab9a637a8f to your computer and use it in GitHub Desktop.
CLI tutorial - step 2
#!/usr/bin/env node
const program = require('commander');
const { join } = require('path');
const fs = require('fs');
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((todo) => {
const data = getJson(todosPath);
data.push({
title: 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