Issues Plaguing My Asynchronous JavaScript Implementation

class FileChecker {
    constructor() {
        this.arguments = process.argv.splice(2);
        this.fileToCheck = this.arguments[0];
        this.directoryToSearch = this.arguments[1] ? this.arguments[1] : '';

        this.currentDirectory = process.cwd();
        this.finalDestination = `${this.currentDirectory}\\` + this.directoryToSearch;

        //Issue Area
        if(this.checkIfFileExists(this.fileToCheck, this.finalDestination)) console.log("FILE EXISTS")
        else console.log("FILE DOES NOT EXIST");
    }

    async checkIfFileExists(file, directory) {
        try {
            let files = await fs.readdir(directory);
          
            return files.includes(file);
        } catch(error) {
            console.log("Error: ", error)
            return false;
        }
    }
}

I am attempting to verify the presence of a file in a directory using promises for file system operations. However, the problematic section consistently returns true, and I am running low on solutions.

Answer №1

When you use if (this.fileExists...), it is essentially the same as if (true) because this.fileExists always returns a Promise, which is automatically converted to a boolean value of true

Instead, it is recommended to call fileExists with await and wrap this call in an IIFE function

Remember to add a semicolon at the beginning of the IIFE function to prevent concatenation with the previous line (this.destination(async...))

class Main {
  constructor() {
    this.argument = process.argv.splice(2)
    this.fileToCopy = this.argument[0]
    this.destination = this.argument[1] ? this.argument[1] : ''

    this.callAdress = process.cwd()
    this.finalAdress = `${this.callAdress}\\` + this.destination

    ;(async () => {
      if (await this.fileExists(this.fileToCopy, this.finalAdress))
        console.log('EXISTS')
      else console.log('DOESNT EXISTS')
    })()
  }

  async fileExists(file, path) {
    try {
      let files = await fs.readdir(path)

      return files.includes(file)
    } catch (e) {
      console.log('ERROR', e)
      return false
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure an AJAX get-request waits for the page to finish rendering before providing a response?

I've been working on a Greasemonkey Script for a specific section of this website (Site1). Site1 offers various deals and discounts, and my script is designed to perform the following task: When a user visits an offer on Site1, the script checks with ...

Discovering all input elements by utilizing nextAll in jQuery

Here is the HTML structure: <div class="field phone"> <input type="text" maxlength="3" /> </div> <div class="field phone number1"> <input type="text" maxlength="3" /> & ...

Caching of audio files in React streaming is enabled

My dilemma lies in the fact that despite creating a new file in the back-end, the <PlaySound /> component continues to play the old sound file rather than the updated one. Although the sound file maintains the same name and path, its content differs. ...

How to use Javascript to pause an HTML5 video when closed

I am new to coding and currently working on a project in Adobe Edge Animate. I have managed to create a return button that allows users to close out of a video and go back to the main menu. However, I am facing an issue where the video audio continues to p ...

Increasing Taxes and Boosting the Overall Cost

How can we set up a system where taxes are bypassed by default unless otherwise specified when placing an order? Let's take a look at the following text box: <input class="txt1" type="text" name="subtotal" value="" id="subtotal" size="16" ta ...

Calculating a Price Quote

I have created a dynamic quote calculator for a Next.js project that allows users to calculate prices based on word count and selected languages. Currently, the price is calculated using a fixed rate of 0.05 per word. 'use client'; import { useS ...

I am unable to view the map on my webpage. This issue only arises when I apply a CSS style to it

Hey there! I'm having trouble displaying a map on my website. For some reason, the map is not showing up even after updating the Google secret key in my code: <?php session_start(); include '../../WSweb/serv.php'; if(isset($_SESSION[&a ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...

How to retrieve the outcome of a stored procedure using node.js

Is it possible to retrieve multiple select results from distinct tables (many rows) in just one stored procedure in mysql and then access those results in nodejs? In .NET with SQL Server, we can use "sqlnextresult" for this purpose. VIEW IMAGE FROM STORE ...

Generate a dynamic JSON object using JavaScript and then deliver it back

I'm dealing with a function that is supposed to return a JSON object in this format: this.sampleFunction = (x, filename) => { if (x.isPresent()) { return { 'result': true }; } else { return { 'result&apos ...

Issue with xsl:include functionality in a Firefox extension

I've been working on a Firefox extension that utilizes XSL transformations with no issues. However, I encountered a problem when trying to perform an xsl:include from the XSL stylesheet. Upon importing the XSL stylesheet containing an xsl:include stat ...

Using AngularJS to Apply a Class with ng-repeat

Using ng-repeat in my markup, I am trying to add text to each li element and also include an additional class (besides the 'fa' class). This is what I have done so far: <ul class='social-icons' ng-repeat="social in myCtrl.socialArr" ...

How can I trigger an Iframe JavaScript function from within my webpage?

I have an Iframe within my page, with the following JavaScript code: function getTotSeats(){ window.WebAppInterface.showToast(document.forms[0].txtSeat_no.value); return document.forms[0].txtSeat_no.value; } I would like to call the above Jav ...

Creating a Custom FlatList Content Container with React Native

Is it possible to customize FlatList items with a custom component? I want to create a setup where my FlatList items are encapsulated within a custom component similar to the following: <ScrollView pt={8} px={16} pb={128} > <Card e ...

What steps do I need to take to adjust this function based on the timezone?

Is there a way to retrieve the current time based on a specific timezone of my choice? let getCurrentTime = () => { var today = new Date(); var hh = String(today.getHours()) var mm = String(today.getMinutes()) //January is 0! var ss = ...

Navigating to Protected Mobile Platform

I am experiencing an issue with accessing a .NET website with SSL on my Blackberry device. When I try to view the site, I receive the message "HTTP ERROR 403 FORBIDDEN - You're not authorized to view this page. Please try loading a different page". Th ...

"Utilizing Trackball controls, camera, and directional Light features in ThreeJS version r69

I am struggling to synchronize trackball controls and camera with the directional light. Here is my situation: I start by initializing an empty scene with a camera, lights, and controls. Then, I load a bufferGeometry obj, calculate its centroid, and adjus ...

Deleting outdated files in a temporary uploads directory - NodeJS best practices

My process for removing old files from a tmp upload directory involves the code below: fs.readdir( dirPath, function( err, files ) { if ( err ) return console.log( err ); if (files.length > 0) { files.forEach(function( file ) { ...

Tips on incorporating CKEditor4 wiris MathML formulas into react JS

I am having trouble displaying MathML in the DOM. When I try to render it, the output is not showing correctly in the Editor. I am utilizing CKEditor4 Let me share the code below to provide more context on what I have attempted so far App.js file: impo ...

Ways to sort items in an array according to their attributes

Is there a way to filter objects within an array based on their properties? Here is the current code I am using: products = [ { title: "Bambu shorts 2.0" }, { title: "Bambu shorts 2.0" }, { title: ...