реагировать на родную библиотеку fs, не записывающую файлы

когда я использую response-native-fs для создания файла, приходит успех в обратном вызове, но файла нет в моей библиотеке android / data / com.myapp / files / test.txt.

В logcat нет ошибок, поэтому мне интересно, почему мой код с простым App.js не работает.

    /**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ToastAndroid
} from 'react-native';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});
var RNFS = require('react-native-fs');
 // create a path you want to write to
 var path = RNFS.DocumentDirectoryPath + '/test.txt';
export default class App extends Component {
  onSave = () => {
    RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8')
.then((success) => {
 console.log('FILE WRITTEN!');
})
.catch((err) => {
 console.log(err.message);
});
  }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <TouchableOpacity onPress={() => this.onSave()}>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        </TouchableOpacity>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

Мне нужно записать log.txt в папку приложения, но невозможно создать новый файл. Буду признателен за любую помощь или предложение.

react-native init myapp cd myapp yarn добавить response-native-fs реакция-native ссылка response-native-fs react-native run-android


person Vojtěch Prchal    schedule 28.03.2018    source источник


Ответы (2)


Можете ли вы попробовать заменить DocumentDirectoryPath на ExternalStorageDirectoryPath.

person HSBP    schedule 28.03.2018
comment
Конечно, я пробовал, но проблема та же. Ошибок нет, только FILE WRITTEN отображается в logcat. РЕДАКТИРОВАТЬ: извините, я заглянул в другой каталог. Мой файл был сохранен в корень внутреннего хранилища, но я подумал, что сохранить там файлы невозможно. Как приступить к работе DocumentDirectoryPath? - person Vojtěch Prchal; 28.03.2018
comment
ExternalStorageDirectoryPath требует дополнительного разрешения: не лучше ли ExternalDirectoryPath? - person Juanpa; 31.07.2019

Вы можете использовать try с RNFS.LibraryDirectoryPath

var url = path let fileName = path.split (/). pop () // console.log ('fileName', fileName) var ext = this.extention (url); ext =. + ext [0]; const localFile = ${RNFS.LibraryDirectoryPath}/${fileName}; // console.log ('localFile', localFile)

        const options = {
            fromUrl: path,
            toFile: localFile,
            fileCache: true
        };

        if (await RNFS.exists(localFile)) {
            FileViewer.open(localFile, { displayName: this.props.route.params.conversationSubject });
        } else {
            await RNFS.downloadFile(options).promise
                .then((res) => {
                    // console.log('res', res)
                    FileViewer.open(localFile);
                })
                .then((res) => {
                    // success
                    // console.log("success", res);
                })
                .catch(error => {
                    // error
                    console.log("Attachment open error: ", error);
                });
        }
person Menon Hasan    schedule 31.05.2021