Array of File Names in a Directory

How to get an array of file names in an app directory?

I have about 1000 icons in my asset folder that I want to include like:

_loadResourcesAsync = async () => {
  return Promise.all([
    Asset.loadAsync([
      require('.assets/icons/1.png'),
      require('.assets/icons/2.png'),
      ...
      ...
      ...
    ]),
  ]);
};

but I don’t want to manually enter it. I need an array that includes all the requires to my files.

I would write a script that creates a file, assets.js that export defaults an Array. This would then be used within your _loadResourcesAsync method.

The assets.js file should look roughly like:

export default [
  require('.assets/icons/1.png'),
  require('.assets/icons/2.png'),
];

Now, to actually generate this file, I’d make a node script (and accompanying package.json run script) that uses fs.readdir to figure out what the paths are statically, then just build a string that looks roughly similar to the export default I have above.

For added benefit, I’m a fan of running my generated code through require('prettier').format.

Thanks for the reply, I have already tried your method before posting.
fs.readdir is not supported within react-native application since react-native is not a node.js.

Unless, assuming that you have already made this method working in production, I think (correct me if I am wrong) running a script from package.json runs on node.js?

I think to access the filesystem we have to use:


async componentWillMount() {
    const fileUri = 'file://..../src/assets/icons';
    filesArray = await Expo.FileSystem.readDirectoryAsync(fileUri);
}

But, I don’t know how to get the path (fileUri) to my application asset directory.

Expo.FileSystem.documentDirectory doesn’t point to the application directory.

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.