Setting up a new folder in the internal storage within a React Native Expo environment

In my React Native Expo project, I am utilizing two functions to store data in a JSON file and then save the file to internal storage. However, the code currently asks for permission to store inside a chosen folder, but does not create the "ProjectName" folder before creating the file. Despite trying various methods, I have been unable to achieve the desired outcome of creating the folder first and then saving the file within it. Can anyone provide insight on how to accomplish this?

Here are the two functions that I have attempted:

const saveJSONToFile = async (fileName, jsonData, mimetype) => {
        const directory = FileSystem.documentDirectory + 'my-project/';
        const fileUri = directory + fileName + '.json';
        try {
            await FileSystem.makeDirectoryAsync(directory, { intermediates: true });
            await FileSystem.writeAsStringAsync(fileUri, JSON.stringify(jsonData));
            console.log('File URI:', fileUri);
        } catch (error) {
            console.error('Error saving JSON data:', error);
        }
        await saveFile(fileUri, fileName, mimetype);
    };
const saveFile = async (uri, filename, mimetype) => {
        if (Platform.OS === "android") {
            const permissions = await FileSystem.StorageAccessFramework.requestDirectoryPermissionsAsync();
            if (permissions.granted) {
                const base64 = await FileSystem.readAsStringAsync(uri, { encoding: FileSystem.EncodingType.Base64 });
                await FileSystem.StorageAccessFramework.createFileAsync(permissions.directoryUri+'/ProjectName/', filename, mimetype)
                    .then(async (uri) => {
                        await FileSystem.writeAsStringAsync(uri, base64, { encoding: FileSystem.EncodingType.Base64 });
                    })
                    .catch(e => console.log(e));
            } else {
                await shareAsync(uri);
            }
        } else {
            await shareAsync(uri);
        }
    };

Answer №1

Dealing with a similar situation, I took the approach of setting up the necessary folders during my app's initialization process. The following code snippet effectively resolved my issue. Make adjustments based on your requirements and ensure it is executed prior to any saving operations.

  const imageDirectory = fileUtils.getPath('image');
  const videoDirectory = fileUtils.getPath('video');
  const audioDirectory = fileUtils.getPath('audio');
  const cacheDirectory = fileUtils.getPath('cache');
  const documentDirectory = fileUtils.getPath('document');

  const directoryCreateConfig = {
    intermediates: true,
  };

  try {
    const response = await Promise.all([
      FileSystem.getInfoAsync(imageDirectory),
      FileSystem.getInfoAsync(videoDirectory),
      FileSystem.getInfoAsync(audioDirectory),
      FileSystem.getInfoAsync(cacheDirectory),
      FileSystem.getInfoAsync(documentDirectory),
    ]);
    const [image, video, audio, cache, document] = response;
    const directoriesToCreate = [];
    if (!image.exists) {
      directoriesToCreate.push(imageDirectory);
    }
    if (!video.exists) {
      directoriesToCreate.push(videoDirectory);
    }
    if (!audio.exists) {
      directoriesToCreate.push(audioDirectory);
    }
    if (!cache.exists) {
      directoriesToCreate.push(cacheDirectory);
    }
    if (!document.exists) {
      directoriesToCreate.push(documentDirectory);
    }

    await Promise.all(
      directoriesToCreate.map(x =>
        FileSystem.makeDirectoryAsync(x, directoryCreateConfig),
      ),
    );
  } catch (error) {
    await Promise.all([
      FileSystem.makeDirectoryAsync(imageDirectory, directoryCreateConfig),
      FileSystem.makeDirectoryAsync(videoDirectory, directoryCreateConfig),
      FileSystem.makeDirectoryAsync(audioDirectory, directoryCreateConfig),
      FileSystem.makeDirectoryAsync(cacheDirectory, directoryCreateConfig),
      FileSystem.makeDirectoryAsync(
        documentDirectory,
        directoryCreateConfig,
      ),
    ]);
  }

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

Position the previous and next buttons next to the thumbnail images

I've implemented the cycle2 jQuery plugin on my website successfully, but I'm facing an issue with positioning the prev and next buttons next to my thumbnails. I want them to be aligned with the first and last thumbnail without relying on absolut ...

Having trouble deleting a Repeatable Job from the Bull queue in Node.js

Upon attempting to utilize the removeRepeatableByKey method, I encountered an error stating that removeRepeatableByKey is not a function. Specifically, it mentioned that queue_1.taskQueue.removeRepeatableByKey is not a function. Furthermore, I am facing d ...

Attempting to manipulate information within the @click event handler embedded within a v-for loop

I am using a v-for loop to select dialog boxes that I want to open. <v-card @click="page.model = true"> In this code, page.model is being used as the v-model for a v-dialog component. data() { return { dialog1: false, dia ...

Ways to assign an identification attribute to HTML elements within innerHTML

Utilizing Ajax in conjunction with php $("#test1").click( .... function(data){ document.getElementById("test2").innerHTML=data; } ) php will return the data echo "<input type='text' id='test'>"; Seeking adv ...

Is it possible to include spaces in a JavaScript alert message?

Is it possible to add spaces in an alert message? I have been trying to include spaces in my alert messages, but the alerts do not appear when there are spaces. Example where it works: https://jsfiddle.net/yczrhztg/ Example where it doesn't work: ht ...

Check for compatibility of overflow:scroll with mobile browsers

Is there an easy JavaScript method that works across different devices and libraries? I am looking to assign a class to the html element in order to enable scrollable containers on mobile devices when needed. I want to follow a similar approach to Modern ...

Error in tabs.onUpdated argument in Firefox WebExtensions

I am currently working on developing a straightforward webExtension for Firefox and I would like to implement tabs.onUpdated with a filter. I found an example on the Mozilla website that I decided to use: const pattern1 = "https://developer.mozilla.org/*" ...

Stylish hover effects displayed on disabled button using Styled Components

I am currently working on a button using Styled Components. However, even when the button is in a disabled state (:disabled), it still exhibits hover behavior that should not be present. I am wondering if there is a proper way to prevent hover effects when ...

Error message: When initiating AJAX requests in ASP.NET, the function is not defined for undefined

I recently followed a tutorial on creating AJAX requests for CRUD operations in an AngularJS application. However, upon trying to perform an AJAX request to retrieve data from the database, I encountered the following error when launching my application: ...

Iterating over images and displaying them in Laravel's blade templating engine, updating outdated Angular code

Currently, I am in the process of transitioning an Angular repeat function used for displaying images on our website (built with Laravel). The goal is to eliminate Angular completely and handle everything using Laravel loops in the blade template. I have ...

Exploring best practices for transmitting JavaScript objects and arrays via forms to servers (JSON/??)

I would like to understand what would be the most effective approach to achieve this: Based on a user selection, generate a list of "selected items" in the following format: {items {categoryString {tag_id1 {[fr]=>itemFR, [en]=>itemEN} {c ...

Having trouble locating the name 'angular' in TypeScript error message

I have completed all the necessary settings, such as adding the typescript compiler in webstorm and installing tsd with npm. However, I am still encountering an error stating 'Cannot find name Angular'. tsd.json { "version": "v4", "repo": ...

Utilizing shared state in React components through props

Currently, I am utilizing a shared global state in the following manner: interface DashboardProps extends React.Props<Dashboard> { globalState? : GlobalState } export class Dashboard extends React.Component<DashboardProps, any>{ } Withi ...

What could be causing the lack of updates for a watched object in vue?

Although there are many similar questions on this topic, mine has a unique twist. After delving into reactivity in depth, I feel like I have a solid grasp of the concept. However, one thing continues to baffle me: Summary: Why does a watched property det ...

Utilize string variables within TypeScript's enumeration feature

Can string variables be used in enums in TypeScript? Strings can be used in enum like so: enum AllDirections { TOP = 'top', BOTTOM = 'bottom', LEFT = 'left', RIGHT = 'right', } However, trying to use variab ...

Steps for extracting a portion of the current page's URL

Can someone help me extract a specific part of the current URL using JavaScript? The URL looks something like this: I need to isolate the number "3153038" from the URL and store it in a JavaScript variable. Thank you! ...

I'm encountering a "confirm" error within the data table. Any suggestions on how to resolve this issue?

When I try to use two datatables columns in confirm, an error occurs when the text 'do you want cancel?' is displayed. The issue seems to be with the text itself and not the code. How should we go about fixing this problem? This is my current cod ...

Is the term "filter" considered a reserved keyword in Angular, Javascript, or ASP.Net MVC?

When using angularJS to call an ASP.Net MVC controller from a service, I encountered an issue with one of the parameters: $http({ method: "get", url: "ControllerMethod", params: { param1: param1Value, pageNumber: pageNumber, ...

React throwing an error when attempting to include a Link component from react-router-dom

Currently working on a React app and encountering an issue while trying to add the Link component from the react-router-dom package. The main routes are defined in the App.js file structured as follows: https://i.stack.imgur.com/BF8M8.png The <Header ...

What are the steps for integrating a CMS with my unique website design?

Currently, I am in the process of creating a unique website for a client using my own combination of html, css, and JavaScript. There is also a possibility that I may incorporate vueJS into the design. The client has expressed a desire to have the ability ...