Home > Back-end >  If/Else If block not activating with node's 'fs' module
If/Else If block not activating with node's 'fs' module

Time:10-08

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.

CodePudding user response:

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.

CodePudding user response:

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 :) 
    }
};
  • Related