Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

File System Access API

Olivier MATROT edited this pageDec 20, 2019 ·82 revisions

RNFetchBlob.fs

File System API was introduced in0.5.0, including the following methods

Differences between File Source

fs APIs provides file access ability to your app, there're generally 3 kinds of file you may need to know when usingfs APIs.

Normal Files

These files are created by your app usingfs, orfetch API, you can do any operation on these files.

Asset Files

Assets files are compiled into the app bundle so generally they're onreadonly mode, only the following operations work on asset files.

  • cp
  • readFile
  • readStream
  • stat

You can also pass a path of asset file to body of afetch request by wrap it usingfs.asset.

const{ fs, fetch, wrap}=RNFetchBlobfetch('POST','http://myupload.com/upload',{'Content-Type' :'application/octet-stream'},wrap(fs.asset('my-asset-file.png')))

For iOS: In order to access asset files on iOS they need to beadded first.They can then be accessed via:

RNFetchBlob.fs.stat(fs.dirs.MainBundleDir+'/whatever/files/you/added.mp3').then(stats=>{...});

For Android: The android equivalent to the above file access would be:

RNFetchBlob.fs.stat(fs.asset('/whatever/files/you/added.mp3').then(stats=>{...});

Gradle will compress bundled assets by default. In order to interact with asset files with this module, compressionmust be disabled. Please seeHow to access files from assets for more detail.

Files from Camera Roll

Files come fromCameraRoll has a different kind of URI, which should looks likeassets-library:// on IOS andcontent:// on Android, these files are just like asset files.

  • These files arereadonly, youCAN NOT change them.
  • YouCANcopy andread these files.
  • YouCAN pass these kind of URI to body offetch request directly (usewrap).

dirs

This constant is a hash map containing commonly used folders:

  • DocumentDir
  • CacheDir
  • MainBundleDir (Can be used to access files embedded on iOS apps only)
  • DCIMDir (Android Only)
  • DownloadDir (Android Only)
  • MusicDir (Android Only)
  • PictureDir (Android Only)
  • MovieDir (Android Only)
  • RingtoneDir (Android Only)
  • SDCardDir (0.9.5+ Android Only)
constdirs=RNFetchBlob.fs.dirsconsole.log(dirs.DocumentDir)console.log(dirs.CacheDir)console.log(dirs.DCIMDir)console.log(dirs.DownloadDir)

If you're going to make downloaded file visible in AndroidDownloads app, please seeShow Downloaded File and Notification in Android Downloads App.

createFile(path, data, encoding):Promise

path:string

The path which this new file will be created.

data:string |Array<number>

Content of the new file, whenencoding isascii, this argument shoud be an array contains number 0~255.

encoding:utf8 |base64 |ascii |uri

Encoding of content.

the following expressions are equivalent.

constfs=RNFetchBlob.fsconstbase64=RNFetchBlob.base64fs.createFile(NEW_FILE_PATH,'foo','utf8')fs.createFile(NEW_FILE_PATH,[102,111,111],'ascii')fs.createFile(NEW_FILE_PATH,base64.encode('foo'),'base64')fs.createFile(PATH_TO_WRITE,PATH_TO_ANOTHER_FILE,'uri')

writeFile(path:string, content:string | Array, encoding:string):Promise

0.6.0

path:string

The path of the file to write.

content:string |Array<number>

Data that write to thepath, should be an utf8/base64 encoded string, or an array containing numbers between 0-255.

encoding:utf8 |base64 |ascii |uri

Encoding of input data.

writeFile API replaces content in the file, if you're going to append data to existing file, you should useappendFile orwriteStream.

// write UTF8 data to fileRNFetchBlob.fs.writeFile(PATH_TO_WRITE,'foo','utf8').then(()=>{ ...})// write bytes to fileRNFetchBlob.fs.writeFile(PATH_TO_WRITE,[102,111,111],'ascii').then(()=>{ ...})// write base64 data to fileRNFetchBlob.fs.writeFile(PATH_TO_WRITE,RNFetchBlob.base64.encode('foo'),'base64').then(()=>{ ...})// write file using content of another fileRNFetchBlob.fs.writeFile(PATH_TO_WRITE,PATH_TO_ANOTHER_FILE,'uri').then(()=>{ ...})// the file should have content// foo

writeStream(path:string, encoding:string):Promise

0.5.0

path:string

The path to the file the stream is writing to.

encoding:utf8 |base64 |ascii

Encoding of input data.

append:boolean(optional, default tofalse)

Will new data append after existing file or not.

CallingwriteStream method will returns a Promise, which resolves aRNFetchBlobWriteSteam instance when stream opened successfully.

// write utf8 dataRNFetchBlob.fs.writeStream(PATH_TO_WRITE,'utf8').then((stream)=>{stream.write('foo')returnstream.close()})// write ASCII dataRNFetchBlob.fs.writeStream(PATH_TO_WRITE,'ascii').then((stream)=>{// write char `f`stream.write([102])// write char `o`, `o`stream.write([111,111])returnstream.close()})// write BASE64RNFetchBlob.fs.writeStream(PATH_TO_WRITE,'base64').then((stream)=>{stream.write(RNFetchBlob.base64.encode('foo'))returnstream.close()})

appendFile(path:string, content:string | Array<number>, encoding:string): Promise<number>

0.6.0

path:string

The path of the file to write.

content:string |Array<number>

Data that write to thepath, should be an utf8/base64 encoded string, or an array contains numbers between 0-255.

encoding:utf8 |base64 |ascii |uri

Encoding of input data.

appendFile is going to appendcontent after existing data. If you want to overwrite the existing file content you should usewriteFile orwriteStream.

If the filepath does not exist it will be created (if possible).

appendFile returns a promise that resolves with the number of bytes that were written. Note that for UTF-8 strings the size does not necessarily equal the number of characters.

// write UTF8 data to fileRNFetchBlob.fs.appendFile(PATH_TO_WRITE,'foo','utf8').then(()=>{ ...})// write bytes to fileRNFetchBlob.fs.appendFile(PATH_TO_WRITE,[102,111,111],'ascii').then(()=>{ ...})// write base64 data to fileRNFetchBlob.fs.appendFile(PATH_TO_WRITE,RNFetchBlob.base64.encode('foo'),'base64').then(()=>{ ...})// the file should have content// foofoofoo// write file using content of another fileRNFetchBlob.fs.appendFile(PATH_TO_WRITE,PATH_TO_READ_FROM,'uri').then(()=>{ ...})

readFile(path, encoding):Promise

0.6.0

path:string

Path of the file to file.

encoding:string

Decoder to decode the file data, should be one ofbase64,ascii, andutf8, it usesutf8 by default.

Read the file from the given path, if the file is large, you should consider usereadStream instead.

RNFetchBlob.fs.readFile(PATH_TO_READ,'base64').then((data)=>{// handle the data ..})

NOTICE: On iOS platform the directory path will be changed every time you access to the file system. So if you need read file on iOS, you need to get dir path first and concat file name with it.

// fileUri is a string like "file:///var/mobile/Containers/Data/Application/9B754FAA-2588-4FEC-B0F7-6D890B7B4681/Documents/filename"if(Platform.OS==='ios'){letarr=fileUri.split('/')constdirs=RNFetchBlob.fs.dirsfilePath=`${dirs.DocumentDir}/${arr[arr.length-1]}`}else{filePath=audioDataUri}

hash(path, algorithm): Promise

0.10.9

path:string

Path to the file.

algorithm: 'md5' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512'

The hash algorithm to use.

Read the file from the given path and calculate a cryptographic hash sum over its contents. The result is encoded as a hexstring.

RNFetchBlob.fs.hash(PATH_TO_READ,'sha256').then((hash)=>{// ..})

readStream(path, encoding, bufferSize, interval): Promise<RNFBReadStream>

0.5.0

path:string

The path to the file the stream is reading from.

encoding:string

Encoding of the data.

bufferSize:number (optional, -1 to process UTF8 files line by line, see below)

Buffer size of read stream, default to4096 and4095(when encoding isbase64)

interval:number (optional, default is 10, -1 to disable)

0.9.4This argument is introduced in 0.9.4, which limits the event dispatch frequency when sending chunks to JS context. You should set appropriate value along with bufferSize when reading large file. The number specifies the amount of timein milliseconds.

readStream returns a promise which will resolveRNFetchBlobReadStream.

RNFetchBlob.fs.readStream(PATH_TO_READ,'utf8').then((stream)=>{letdata=''stream.open()stream.onData((chunk)=>{data+=chunk})stream.onEnd(()=>{console.log(data)})})

readStream could also be used to process UTF8 files one line at a time by sending -1 to the bufferSize and utf8 to encoding. This will, for instance, be very usefull to replay a stream of data events stored in a .csv file at a specified cadence by tweaking the interval parameter.

RNFetchBlob.fs.readStream(// file pathPATH_TO_READ,// encoding, should be `utf8`"utf8",// Buffer size special value to read a text file line by line-1,// Wait 5 ms between onData events (200 Hz event stream)1000/200).then(ifstream=>{this.csvStream=ifstream;ifstream.open();this.emitter=newObservable(subscriber=>{ifstream.onData(chunk=>{// chunk will be a string when encoding is 'utf8'logging.logWithTimestamp(`Received [${chunk}]`);subscriber.next(chunk);});ifstream.onError(err=>{logging.logWithTimestamp(`oops [${err}]`);subscriber.error(err);this.csvStream=null;});ifstream.onEnd(()=>{subscriber.complete();this.csvStream=null;});});

mkdir(path:string):Promise

0.5.0

Create a directory namedpath

RNFetchBlob.fs.mkdir(PATH_TO_CREATE).then(()=>{ ...}).catch((err)=>{ ...})

The function rejects with an error if the given path already exists.

ls(path:string):Promise<Array>

0.5.0

List files and directories in apath

RNFetchBlob.fs.ls(PATH_TO_LIST)// files will an array contains filenames.then((files)=>{console.log(files)})

mv(from:string, to:string):Promise

0.5.0

Move a file's location

RNFetchBlob.fs.mv(FROM_PATH,TO_PATH).then(()=>{ ...}).catch(()=>{ ...})

cp(src:string, dest:string):Promise

Copy a file.

RNFetchBlob.fs.cp(SRC_PATH,DEST_PATH).then(()=>{ ...}).catch(()=>{ ...})

exists(path:string):Promise

0.5.0

Check if a file exist atpath

RNFetchBlob.fs.exists(PATH_OF_FILE).then((exist)=>{console.log(`file${exist ?'' :'not'} exists`)}).catch(()=>{ ...})

isDir(path:string):Promise

Check the file atpath is a directory or not. Resolves withfalse when the path is not a directory, or it does not exists.

RNFetchBlob.fs.isDir(PATH_OF_FILE).then((isDir)=>{console.log(`file is${isDir ?'' :'not'} a directory`)})

unlink(path:string):Promise

0.5.0

Delete a file or an entire folder atpath.Note that there will be no error if the file to be deleted does not exist.

RNFetchBlob.fs.unlink(path).then(()=>{ ...}).catch((err)=>{ ...})

lstat(path:string):Promise<RNFetchBlobStat>

0.5.0

Get statistic data of files in a directory, the result data will be an array ofRNFetchBlobStat object.

RNFetchBlob.fs.lstat(PATH_OF_A_FOLDER).then((stats)=>{}).catch((err)=>{})

stat(path:string):Promise<RNFetchBlobStat>

0.5.0

Similar get statistic a data or a directory. the result data will be aRNFetchBlobStat object.

RNFetchBlob.fs.stat(PATH_OF_THE_TARGET).then((stats)=>{}).catch((err)=>{})

scanFile(path:string):Promise (Android Only)

0.5.1

ConnectMedia Scanner and scan the file. seeAndroid Media Scanner, and Downloads App Support chapter for more information.

asset(filename:string):string

0.6.2

When the file comes from app bundle assets, you should use this method to prepend a prefixbundle-assets:// so that the fs APIs know this is a file in app bundle.

letpath=RNFetchBlob.fs.asset('my-asset.jpg')

Asset files arereadonly, therefore there's some limitations when dealing with assets. Please seeDifferences between File Source for more detail.

df():Promise<{ free: number, total: number }>

0.10.0

Get free and total disk space of the device.returns an object with propertiesfree andtotal on iOS.

Example:

RNFetchBlob.fs.df().then((response)=>{console.log('Free space in bytes: '+response.free);console.log('Total space in bytes: '+response.total);})

For Android:

returns an object with propertiesinternal_free,internal_total,external_free andexternal_total on android./wiki/File-System-Access-API#differences-between-file-source) for more detail.

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp