Coder Social home page Coder Social logo

todolist-nodeconsola's Introduction

Consola Interactiva

Utilizar paquete Colors para mejorar la estética de las opciones en consola.

Leer por consola

Utilizar paquete readLine propio de node:

    const readLine = require('readline').createInterface({
        input: process.stdin,
        output: process.stdout
    })

    readLine.question('Seleccione una opción: ', (opc) => {
        console.log(opc);
        readLine.close();
    })

Inquirer

Permite crear interfaces de consola con mayores funcionalidades

npm install --save inquirer

Modificar package.json

La versión 9 de inquirer ahora requiere el uso de módulos de ECMAScript.

Se agrega el "type": "module"

{
  "name": "todolist-nodeconsola",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "colors": "^1.4.0",
    "inquirer": "^9.1.5"
  }
}

Se cambian require por imports y se cambia la forma de exportar:

import inquirer from 'inquirer';
 
import colors from 'colors';
const miFuncion = () => {}

export {
    miFuncion
};

Uso

import colors from 'colors';
import { inquirerMenu, pausa} from './helpers/inquirer.js'

console.clear();

const main = async() => {
    let opc = '';
    do {
        opc = await inquirerMenu();
        console.log(opc);
        if(opc !== '0') await pausa();
    } while (opc !== '0');

}

main();
import inquirer from 'inquirer';
import colors from 'colors';

const preguntas = [
    {
        type: 'list',
        name: 'opcion',
        message: 'Que desea hacer?',
        choices: [
            {
                value: '1',
                name: '1. Crear Tarea'
            },
            {
                value: '2',
                name: '2. Listar Tareas'
            },
        ]
    }
]

const inquirerMenu = async() => {
    console.clear();
    console.log("=======================================".white);
    console.log("              TO-DO LIST              ".blue);
    console.log("         Seleccione una opción        ".green);
    console.log("=======================================\n".white);

    const opt = await inquirer.prompt(preguntas)
    const {opcion} = opt;
    return opcion;
}

const pausa = async() => {
    console.log('\n')
    await inquirer.prompt({
        type: 'input',
        name: 'continuar',
        message: `Presione ${'ENTER'.green} para continuar...\n`,
    })
}

export {
    inquirerMenu,
    pausa
}

Leer por consola y validar

const leerInput = async(mensaje) => {
    const question = [
        {
            type: 'input',
            name: 'desc',
            message: mensaje,
            validate(value){
                if(value.length === 0){
                    return 'Por favor ingrese un valor';
                }
                return true
            }
        }
    ]

    const {desc} = await inquirer.prompt(question);
    return desc;
}

Confirmación

const confirmar = async (message) => {
    const question = [
        {
            type: 'confirm',
            name: 'confirmed',
            message
        }
    ]

    const {confirmed} = await inquirer.prompt(question);

    return confirmed;
}

Selección múltiple

const listadoCheckList = async (tareas=[]) => { 
    const choices = tareas.map((tarea,i) => {

        return {
            value: tarea.id,
            name: `${i+1}. ${tarea.desc}`,
            checked: tarea.completadoEn ? true:false
        }
    })

    const preguntas = [
        {
            type: 'checkbox',
            name: 'ids',
            message: 'Seleccion: ',
            choices
        }
    ]
    const {ids} = await inquirer.prompt(preguntas)
    return ids;
    // Retorna arreglo
}

Guardar y Leer archivo

import fs from 'fs';

// Crear archivo
fs.writeFileSync(archivo,JSON.stringify(data))

// Leer archivo
if(!fs.existsSync(archivo)) return null;
const info = fs.readFileSync(archivo, {encoding: 'utf-8'})
const data = JSON.parse(info);

UUID

Paquete para crear identificadores únicos a nivel mundial.

npm i uuid

import { v4 as uuidv4 } from 'uuid';
id = uuidv4();

Objeto to Array

get ListadoArr(){
    const listado = [];
    Object.keys(this._listado).forEach(key => {
        const tarea = this._listado[key]
        listado.push(tarea)
    })

    return listado;
}

Eliminar de un objeto

borrarTarea(id=''){
    if(this._listado[id]){
        delete this._listado[id];
    }
}

todolist-nodeconsola's People

Contributors

leo-zubiri avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.