Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
If/Else If block not activating with node's 'fs' module

When I try and run my example CLI app (params built with yargs to parse optstrings), it does this error in a fat stack trace: https://streamable.com/v4sih6 (video recording as it is so big)

I don't know what I am doing wrong. Here is my ts code:

import type { Arguments, CommandBuilder } from 'yargs';
import chalk from 'chalk';
import * as logos from '../logos';
import fs from 'fs';

type Options = {
    componentName?: string;
};

export const command: string[] = ["component", "c", "comp"];
export const desc: string = 'Creates a component. Use: "vcli component title" - this makes a new title component (optional).';

export const builder: CommandBuilder<Options, Options> = (yargs) =>
    yargs
        .options({
            componentName: { type: 'string' },
        });

//TODO: Check if component exists

export const handler = (argv: Arguments<Options>): void => {
    const { componentName } = argv;
    if (componentName !== undefined) {
        const timerMsg: string = `${logos.prefix} Component with name '${componentName}' has been successfully created in`
        console.time(chalk.green(timerMsg));
        fs.mkdirSync(`./src/components/${componentName}`);
        fs.writeFileSync(`./src/components/${componentName}/index.tsx`, `import React from 'react';\n\nimport './${componentName}Styles.scss'`);
        console.timeEnd(chalk.green(timerMsg));
    } else if (fs.existsSync(`./src/components/${componentName}`)) {
        console.log(chalk.red(`${logos.prefix} Component ${componentName} already exists!`));
    } else {
        // Write an inquirer.js prompt here to ask for the name of the component :) 
    }
};

Thanks for the help.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The error you are getting is File already exists for src/components/testing

Code that is failing is :

fs.mkdirSync(`./src/components/${componentName}`);

Fix

Check the if not exists before writing i.e. if (!fs.existsSync('./src/components/${componentName}')) should be before you try to make the dir.

about 4 years ago · Juan Pablo Isaza Denunciar

0

If your problem is that this line of code:

fs.mkdirSync(`./src/components/${componentName}`);

is giving you an error because the directory already exists, then you can simply catch that specific error, test for it and ignore it if it's that specific error because this is not really a problem that you need to abort for.

export const handler = (argv: Arguments<Options>): void => {
    const { componentName } = argv;
    if (componentName !== undefined) {
        const timerMsg: string = `${logos.prefix} Component with name '${componentName}' has been successfully created in`
        console.time(chalk.green(timerMsg));

        try {
            fs.mkdirSync(`./src/components/${componentName}`);
        } catch(e) {
            // only throw error if the error is not because the directory
            // already exists
            if (e.code !== 'EEXIST') {
                throw e;
            }
        }

        fs.writeFileSync(`./src/components/${componentName}/index.tsx`, `import React from 'react';\n\nimport './${componentName}Styles.scss'`);
        console.timeEnd(chalk.green(timerMsg));
    } else if (fs.existsSync(`./src/components/${componentName}`)) {
        console.log(chalk.red(`${logos.prefix} Component ${componentName} already exists!`));
    } else {
        // Write an inquirer.js prompt here to ask for the name of the component :) 
    }
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda