Analyzing the list of paths that are passed to the function

I am looking for assistance in creating an asynchronous "getTypes" function that can analyze a list of paths and return an array describing the type of content in each path. The function should handle all cases efficiently and in case of any errors during the operation, it should return "null" for that specific path. I have attempted to write a function myself but encountered issues.

const getTypes = (arr) => {
  const prom = arr.reduce((acc, path) => (
    acc.then((data) => {
       return fs.stat(path).isFile() ? 'file' : 'directory';
     })
    .catch(() => null)
  ), Promise.resolve());
  return prom;
}

This is how it should operate:

getTypes(['/etc', '/etc/hosts', '/undefined']).then(console.log);
// ['directory', 'file', null]

I am struggling with this implementation, seeking help from someone who can assist. Thank you!

Answer №1

Strategy 1

async function fetchFileTypes(array) { // Indicate the function as async
   return Promise.all(array.map(async (path) => { // Promise.all will wait for all mapped calls to be resolved
      try {
          const fileInfo = await fs.stat(path) // fs.stat is async
      } catch(e) {
          return null
      }
      return fileInfo.isFile() ? 'file' : 'directory';
   }));
}

Strategy 2: (Adjustments to original code)

const getFileTypes = array => {
  const promise = array.reduce((acc, path) => {
    acc
      .then(data => {
        return Promise.all([fs.stat(path), Promise.resolve(data)]);
      })
      .then(([fileInfo, data]) =>
        fileInfo.isFile()
          ? [Promise.resolve(data.push("file")), false]
          : [Promise.resolve(data.push("directory")), false]
      )
      .catch(() => Promise.resolve([data, true])) // so the next `then` can have access to data
      .then([data, failed] => failed === true ? Promise.resolve(data.push(null)) : Promsie.resolve(data)
  }, Promise.resolve([]));
  return promise;
};

Strategy 3: (Not resilient to faults. Promise.all will fail if an error occurs in any of the async calls):

function determineFileTypes(array) {
  const promises = array.map(fs.stat);
  return Promise.all(promises).then(stats =>
    stats.map(fileInfo => (fileInfo.isFile() ? "file" : "directory"))
  );
}

Strategy 4: (Making #3 slightly fault-tolerant)

const getFileType = fileInfo => fileInfo.isFile() ? 'file' : 'directory'
const fetchFileStat = path => fs.stat(path).then(getFileType).catch(() => null)
const determineFileTypes = paths => Promise.all(paths.map(fetchFileStat))

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

Prevent the hiding of a select element with jQuery Chosen Select

I am facing difficulty hiding a select element with the chosen-select class if it does not have any elements present. I attempted: $("#Category2").hide(); and also tried removing the chosen-select class before hiding the element: $("#Category2").re ...

Combining two react functions in a synchronized manner

I'm facing a React coding challenge. I need to combine the handleUpdate and handleUpload functions in a synchronous manner so that the state is updated before the function continues executing. I attempted the following code snippet with my suggested e ...

Unable to locate any division element by using document.getElementById

I'm encountering an unusual issue in my code. I am attempting to change the background color of certain divs using Javascript, but for some reason, when I use "document.getElementById", it is unable to find the div and returns NULL. Here is the probl ...

Update the directive automatically whenever a change occurs in the root scope property

I am facing an issue with a directive that generates a random number. My goal is to reload or refresh this directive when a checkbox is toggled. Below is the code I have been using, but unfortunately, it's not working as expected. var app = angular. ...

Storing input field values in JavaScript using the onchange event handler.Would you like a different revision

I am looking to calculate the area by multiplying width and height entered into input fields, and then display the result. Any guidance would be greatly appreciated. Thank you! Here is my current code. const width = document.querySelector("#width"); con ...

Swap out ASP.NET AJAX with jQuery for making ASHX requests

Recently, I have been utilizing the following method to communicate with a Web Proxy for cross domain calls. However, as I am in the process of updating my code and already use jQuery, I am considering dropping ASP AJAX since it is only used for this speci ...

Challenges in Implementing Shadows with Animations in ThreeJS MeshDepthMaterial

I'm facing an issue where casting shadows through transparent parts of my Mesh using the MeshDepthMaterial causes the shadows of animated objects to stop moving along with the animation. You can see an example of this problem here: https://jsfiddle.n ...

The capacity to rotate div containers, adjust their dimensions, and engage with the content within

I'm attempting to design small clickable div boxes that flip 180° when clicked to reveal interactive content. This includes the ability to click links, copy text, or manipulate the content with additional buttons. Although I've successfully ach ...

How can you proactively rebuild or update a particular page before the scheduled ISR time interval in Next.js?

When using NextJS in production mode with Incremental Static Regeneration, I have set an auto revalidate interval of 604800 seconds (7 days). However, there may be a need to update a specific page before that time limit has passed. Is there a way to rebui ...

How to dynamically change the position of an input field within a form using JavaScript and jQuery

I have a form displayed on my website that looks like this: input a input b input c I am wondering if it is achievable to rearrange the order of inputs using jQuery, like so: input a input c input b However, it is important that the data is still ...

An issue arose upon scanning the QR code for whatsapp-web.js, indicating a potential

My WhatsApp web bot encountered issues this week. C:\pinkmeupwabot\node_modules\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:221 throw new Error('Eval ...

Utilizing Jquery in the Customer Portal feature within the Salesforce platform

Struggling to incorporate a Visualforce page with Jquery UI and Salesforce Customer Portal. Unfortunately, Jquery UI seems to be taking precedence over the Standard Salesforce stylesheet. Is there a way to prevent this from happening? Any assistance on t ...

Is there a specific method for organizing cached buffer conversions in Node.js for optimal efficiency?

In a GitHub discussion, it was pointed out that the Map's .has method does not work with buffers because identical buffers are considered as distinct objects. This limitation became apparent when attempting to store buffer string conversions in a map ...

Switch up the position of an element every time the page is refreshed

I have a webpage containing 5 images, each measuring 48px by 48px. I would like these images to be displayed in random positions on the page every time it is loaded. While I am aware that I will need to use CSS and JavaScript for this task (specifically f ...

Performing addition and subtraction calculations with HTML and Javascript

I need help creating a simple HTML table for adding and subtracting values, with a limit of 10 and a minimum of 0. I have two functions set up, additionalAdd and additionalSub, triggered by the onclick event, but I keep getting an error saying that totalAd ...

Having trouble persisting my login status in Selenium using Python

Has anyone experienced issues with logging into Instagram using an automate tab? Previously, I didn't have any problems, but now it seems that Instagram is not allowing users to log in through automation. An error message stating the following appears ...

retrieving data from a php file using ajax for a post request

Utilizing ajax, I have invoked the page search.php: function search(){ var title=$("#search").val(); if(title!=""){ $.ajax({ type:"post", url:"sear ...

Tips for preventing repetition of code in multiple entry points in Rollup

My goal is to use rollup to process a group of input files and generate multiple output files in the dist directory that all have some common code shared between them. Below is my current rollup configuration: import path from 'path'; import pat ...

How can I turn off autocomplete in MUI textfields?

Currently, I am working with the latest version of mui. Within my user contact info form, there is a zip code field that I do not want to be auto completed if the value is null. However, despite my efforts, it continues to autocomplete with the email saved ...

Create queries for relays in a dynamic manner

I'm using Relay Modern for my client GraphQL interface and I am curious to know if it is possible to dynamically generate query statements within Relay Modern. For example, can I change the original query structure from: const ComponentQuery = graphq ...