Skip to content

Instantly share code, notes, and snippets.

@Rikezenho Rikezenho/cli-02.js
Last active Feb 11, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.