Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda