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

How can one include a URL as a "URL parameter" when using Express?

In my Node.js application, I've set up a router to listen for requests at api/shorten/: router.get('api/shorten/:longUrl', function(req, res, next) { console.log(req.params.longUrl); } When I enter something like: http://l ...

The integration of VueJS with Axios and the Google Maps API

Currently following [this][1] guide to develop a Google Map and now I am looking to execute a GET request with Axios: axios.get("http://localhost:8080/mapjson").then(function(response) { }) in order to integrate the information from my JSON file into the ...

What is the proper way to generate an iframe with a width set to "100%" or left empty, rather than width = "100"?

I am currently utilizing vimeowrap to iterate through a playlist of videos. I would like the iframe that is generated by vimeowrap to have either a width and height set to "100%" or nothing at all. For more information on Vimeo Wrap, visit: To see my tes ...

positioning a text input in the center instead of at the top of the page

Hello everyone, I am just starting out with HTML and I have a question. How can I make the Username: <input type="text" name="Username" style="- margin-top: 200px;"> appear in the center of the page instead of at the top? I've tried changing the ...

The request included an unsupported media type of "text/plain;charset=UTF-8". This caused an error in the NextJS API when interacting with Django Rest Framework

Currently diving into the world of web development, I am endeavoring to construct a website utilizing NextJS and Django Rest Framework. While NextJS effectively proxies API endpoints for retrieving data, I find myself grappling with making it work for a PO ...

Ways to incorporate JavaScript code within Reactjs

I am currently working with Reactjs and using Nextjs. I am facing a challenge regarding integrating "index.html" with "index.js". At the bottom of "index.html", there is some JavaScript code that I need to transfer to another file. Can you advise me on w ...

Preserving Foreign Key Relationships in Django Rest Framework Serializers

Within my project, I have two interconnected models named Task and Batch, linked through a Foreign Key field. My goal is to verify the existence of a Batch Object in the database before creating a new Task Object. The Batch object represents the current da ...

What is the best way to display my data as plain text within a paragraph that is enclosed in JSON text using JQuery?

Just starting out with JSON. Currently working with the Coinbase API, which is using JSON format. Check out this code snippet: <%@ page language="java" contentType="text/html; charset=ISO-8859-1"%> <%@ page import="rajendra.arora.bitcoin.Coinba ...

Swagger Issue Resolved: Restriction on Number of Params Set

After setting up this option for my route, I noticed that when accessing the first parameter (page), it correctly returns the value entered in Swagger UI. However, when trying to access the second parameter (genre), it seems to interpret it as a string &ap ...

What is the method for acquiring a dynamic segment in the router of a Next.js 13 application?

Currently in my project, I am using the new App Router in Next.js 13 and MongoDB as the DBMS to fetch data via API. When trying to retrieve all data from a collection, it is successful. However, fetching only one data results in failure. The error message ...

increasing the size of a picture without resorting to a pop-up window

Struggling to implement a product details tab within a table that features a clickable image. When the image is clicked, it should enlarge but the width doesn't adjust accordingly. I'm using bootstrap 5.3 and can't seem to identify the root ...

`user implemented object comparison within a set in unity (es6)`

I am facing an issue where I need to handle multiple values and ensure that only unique ones are used. With the use of node js and access to harmony collections through the --harmony flag, I have considered using a Set as a potential solution. What I am s ...

IE11 and how it handles Typescript and promises

Currently, I am utilizing Typescript version 2.4.2 along with Webpack for compilation purposes. Despite successful compilation, when running my code on IE11, an error 'Promise' is undefined arises. Below is a glimpse of my tsconfig: { "comp ...

Utilizing dynamic content to pass arguments to JavaScript functions

I'm facing a challenging issue that is causing me frustration. While browsing through this platform, I found some potential solutions but encountered a roadblock in implementing them successfully. My current project involves developing an e-commerce p ...

The Print Preview Displays No Content When an External Stylesheet Reference is Included in the Printable HTML Content

Is there a way to print the contents of a DIV on a webpage? Currently, I am using JavaScript to retrieve the contents of the div and then passing it to a new window object where I call the .print() function. The text contents and images are displayed corre ...

The Typescript const assertion translated into Javascript

Is there a way in JavaScript to achieve constant-like behavior similar to TypeScript's const assertion? const arr = [1,2,3,4] as const I am looking for a solution in JavaScript that allows me to create an array that cannot be further mutated. ...

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...

Retrieving the value of a formControl within a formArray is made possible through a reactive form in

How can I retrieve the value of ItemName in my HTML code? When I attempt to use {{invoiceForm.controls[i].items.controls.itemName.value | json}}, it returns as undefined. <form [formGroup]="invoiceForm"> <div formArrayName="items" *ngFor="let ...

Discovering hidden Mixed Content problems on a secured website can be a challenging task

After deploying a simple PWA application on the NGINX server, which was created using Vue CLI, I decided to use hash mode instead of history mode for the Vue router. Even though the website is secure: I am encountering the following errors and I'm n ...

Can you provide instructions for generating a simple menu bar with options utilizing webgl/three.js?

I find the documentation for the three.js 3-D viewer difficult to understand as a beginner. I am curious about the fundamental steps involved in creating a menu bar or selector with options for a 3-D viewer using three.js / WebGL. Additionally, I am inter ...