使用reart-native-fs 在React-Native 中保存文件

For*_*rad 10 javascript react-native

使用react-native-fs该文件在哪里保存文件后?

文档中没有解释,或者我找不到并且很难弄清楚。

And*_*rew 15

创建文件时,必须指定存储文件的目录。在下面的示例中,path变量显示了文件将被写入的位置。

var RNFS = require('react-native-fs');

// create a path you want to write to
// :warning: on iOS, you cannot write into `RNFS.MainBundlePath`,
// but `RNFS.DocumentDirectoryPath` exists on both platforms and is writable
var path = RNFS.DocumentDirectoryPath + '/test.txt';

// write the file
RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8')
  .then((success) => {
    console.log('FILE WRITTEN!');
  })
  .catch((err) => {
    console.log(err.message);
  });
Run Code Online (Sandbox Code Playgroud)

您可以在多个位置存储文件

以下目录可用:

  • MainBundlePath (字符串)主包目录的绝对路径(在 Android 上不可用)
  • CachesDirectoryPath (字符串)缓存目录的绝对路径
  • ExternalCachesDirectoryPath (字符串)外部缓存目录的绝对路径(仅限安卓)
  • DocumentDirectoryPath (字符串)文档目录的绝对路径
  • TemporaryDirectoryPath (字符串)临时目录的绝对路径(回退到 Android 上的缓存目录)
  • LibraryDirectoryPath (字符串)NSLibraryDirectory 的绝对路径(仅限 iOS)
  • ExternalDirectoryPath (字符串)外部文件的绝对路径,共享目录(仅限android)
  • ExternalStorageDirectoryPath (字符串)外部存储的绝对路径,共享目录(仅限android)

所以你所要做的就是选择目录。请注意,这些目录位于设备上。

查看设备上的文件

iOS模拟器

如果你想在你的 iOS 模拟器上找到这个文件,你需要做的就是 console.log 路径,它应该看起来像这样

/Users/work/Library/Developer/CoreSimulator/Devices/2F8BEC88-BF42-4D6B-81D4-A77E6ED8CB00/data/Containers/Data/Application/BC16D2A6-55A2-475C-8173-B650A4E40CF1/Documents/
Run Code Online (Sandbox Code Playgroud)

打开Finder,选择Go to folder

在此处输入图片说明

然后粘贴路径,这将打开文件所在的文件夹。

在此处输入图片说明

安卓模拟器

如果你 console.log 文件的路径,你应该得到这样的东西

/data/user/0/com.awesomeapp/files/
Run Code Online (Sandbox Code Playgroud)

您必须从 Android Studio 运行该应用程序,然后您需要访问Device View Explorer. 你可以通过View-> Tool Windows->Device File Explorer

在此处输入图片说明

然后应该会打开一个看起来像这样的窗口,然后您可以在其中浏览到上面给出的文件路径。

在此处输入图片说明

  • 当我使用此代码在我的物理设备上安装我的应用程序时。在控制台中,我看到文件已写入,但该文件在我的物理设备上在哪里?我如何选择目录? (2认同)