Create a JavaScript function that checks for the existence of a file and returns a

I need to implement a JavaScript function that can determine if a file exists on a web server by using the fetch() method.

Below is my current code snippet:

let result = checkFile("index.html");
console.log("typeof(result) = " + typeof(result));

async function checkFile(file) {
    try {
        let response = await fetch(file);
        if (!response.ok) {
            throw new Error("Network response was not OK");
        } else {
            return true;
        }
    }
    catch {
        return false;
    }
}

After running the function, I noticed that it outputs the following message in the browser console:

"typeof(result) = object"

Why is the output not simply true or false?

Answer №1

To successfully display the output in your console.log, it is recommended to exclude the typeof() method from the code.

Additionally, ensure you are utilizing the await keyword for obtaining the response. For further information, refer to this link: https://www.example.com/js/async-await

You may also have to call the checkFile function within an async function.

Here is a suggested approach:

let fileCheck = await checkFile("index.html");
console.log(`The type of fileCheck is ${fileCheck}`);

async function checkFile(file) {
    try {
        let serverResponse= await fetch(file);
        if (!serverResponse.ok) {
            throw new Error("There was an issue with the network response");
            
        } else {
            return true;
        }
    }
    catch {
        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

Refresh the html page periodically by utilizing ajax every X seconds

Recently, I came across a post discussing the topic of automatically refreshing an HTML table every few seconds. The post can be found here. Currently, I am working with Rails and I want to achieve a similar functionality. However, I specifically want to ...

Attempting to abbreviate repetitive Javascript instructions

I have this functional javascript code, but I feel like there might be a more efficient way to write it. Any suggestions on simplifying this? let searchTerm = 'Some search text'; const isMatch = entry.title.toLowerCase().includes(searchTer ...

The default locale for momentJS is set to zh-tw and I'm having trouble changing it

Currently, I am incorporating the momentJS library into my Angular application by pulling it from a CDN: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script> Although the default locale should be Engli ...

Where should custom PHP code be placed in Prestashop 1.7.5?

Currently, I am facing the challenge of incorporating a custom PHP code snippet into Prestashop's file structure so that it is accessible on all pages such as the cart, categories, and CMS pages. After some research, I have found suggestions to place ...

Unable to assign Angular 2 service data to a variable within the constructor

I am facing an issue in my Angular 2 application where I need to assign the data returned from a service function to a public variable and display it in the HTML view. While the console log shows that the data is successfully fetched, it does not seem to b ...

Steps to turn off popover functionality for a specific child element

Within a container, there are details along with a button. The container exhibits popover behavior upon hovering over it. However, the challenge lies in disabling the popover behavior while hovering specifically over the button within it. You can find th ...

Navigating through various features in nodejs / expressjs

Managing multiple functions in nodejs/expressjs can be a bit confusing for those used to PHP. In PHP, you simply call one function after another, but in node, things work differently with callbacks and potential errors related to undefined variables. Her ...

Tips for accessing an Angular service from different Angular controllers

I am a beginner with angular js and I am currently exploring ways to call the service provided in the code snippet below from a controller. The service is defined as follows. app.factory('myappFactory', ['$http', function($http) { v ...

Creating a variety of NextJS components

Currently delving into NextJS and aiming to showcase a website featuring my various projects created with it. A special "Tag" component functions as a button template that allows custom text passed through props: export default function Tag({val}) { r ...

Attempting to refresh the choices in a dropdown list by sending a request via jQuery leads to specific

I have a Dropdown on my View that looks like this... <div class="editor-field"> @Html.DropDownListFor(model => model.CategoryId, new SelectList(new List<string>(), ""), "Select ...") </div> Within my controller, there is an action ...

Encountering an abundance of concurrent requests using NodeJS and request-promise

I am currently working on a NodeJS project that involves a large array of about 9000 elements containing URLs. These URLs need to be requested using the "request-promise" package. However, making 9000 concurrent GET requests to the same website from the sa ...

Pass an item along with its superclass using express

Is there a way to send an object from an express server and then check the instanceof of that object on the receiving end? I am working on integration tests for express and need to verify the instanceof of the response body. Unfortunately, it seems like t ...

How can I use handlebars to display a video when the user clicks on an image?

I'm currently working on a webpage where I want to be able to show a hidden video when the user clicks on an image tag. I've implemented this using handlebars. Additionally, I want the video to close when the user clicks on another photo. < ...

Remove an item from an Ionic list

I am currently in the process of developing an Ionic to-do list application. I am facing an issue with the delete function where the delete button is not working as expected. When the button is clicked, nothing happens. HTML: <ion-view view-title="To ...

Creating a dialog box that effectively blocks user interaction

Is it possible to implement a blocking dialog box with JavaScript/JQuery/Ajax? I've been working with the JQuery UI dialog box, but using it asynchronously with callback functions has made it more complicated than expected. For example: ans1 = confi ...

What is the method for providing external parameters to a JOI extension?

Perhaps JOI may not be the ideal tool for this particular task, but I am interested in utilizing it if feasible. Essentially, I have a scenario where a user is sending a request to an API to store specific metric data. Certain metrics are restricted based ...

What is the best way to implement dynamic filtering in Nest JS?

I have a unique software application that requires dynamic filtering, but I am facing a challenge with different fields where I cannot specify any field specifically. Can you provide me with some guidance or articles on how to tackle this issue? Here is a ...

Is there a way to dynamically adjust the height of a DIV block?

I have a situation where I need the height of one div to automatically adjust based on changes in the height of another div. var height = jQuery('#leftcol').height(); height += 20; jQuery('.rightcol-botbg').height(height); Unfortun ...

Get detailed coverage reports using Istanbul JS, Vue JS, Vue CLI, Cypress end-to-end tests, and Typescript, focusing on specific files for analysis

I have a VueJS app written in Typescript that I am testing with Cypress e2e tests. I wanted to set up coverage reports using Istanbul JS to track how much of my code is covered by the tests. The integration process seemed straightforward based on the docum ...

creating a randomized location within an HTML element using JavaScript

Trying to figure out how to randomly generate a position within an HTML div. I've come up with a JavaScript function that looks like this: function randomInRange(min, max) { return(Math.floor((Math.random() * (max - min) + 1) + min)); } My ...