No Description

fs.js 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. // Copyright 2016 wkh237@github. All rights reserved.
  2. // Use of this source code is governed by a MIT-style license that can be
  3. // found in the LICENSE file.
  4. // @flow
  5. import {
  6. NativeModules,
  7. DeviceEventEmitter,
  8. Platform,
  9. NativeAppEventEmitter,
  10. } from 'react-native'
  11. import RNFetchBlobSession from './class/RNFetchBlobSession'
  12. import RNFetchBlobWriteStream from './class/RNFetchBlobWriteStream'
  13. import RNFetchBlobReadStream from './class/RNFetchBlobReadStream'
  14. import RNFetchBlobFile from './class/RNFetchBlobFile'
  15. import type {
  16. RNFetchBlobNative,
  17. RNFetchBlobConfig,
  18. RNFetchBlobStream
  19. } from './types'
  20. const RNFetchBlob:RNFetchBlobNative = NativeModules.RNFetchBlob
  21. const emitter = DeviceEventEmitter
  22. const dirs = {
  23. DocumentDir : RNFetchBlob.DocumentDir,
  24. CacheDir : RNFetchBlob.CacheDir,
  25. PictureDir : RNFetchBlob.PictureDir,
  26. MusicDir : RNFetchBlob.MusicDir,
  27. MovieDir : RNFetchBlob.MovieDir,
  28. DownloadDir : RNFetchBlob.DownloadDir,
  29. DCIMDir : RNFetchBlob.DCIMDir,
  30. SDCardDir : RNFetchBlob.SDCardDir
  31. }
  32. /**
  33. * Get a file cache session
  34. * @param {string} name Stream ID
  35. * @return {RNFetchBlobSession}
  36. */
  37. function session(name:string):RNFetchBlobSession {
  38. let s = RNFetchBlobSession.getSession(name)
  39. if(s)
  40. return new RNFetchBlobSession(name)
  41. else {
  42. RNFetchBlobSession.setSession(name, [])
  43. return new RNFetchBlobSession(name, [])
  44. }
  45. }
  46. function asset(path:string):string {
  47. if(Platform.OS === 'ios') {
  48. // path from camera roll
  49. if(/^assets-library\:\/\//.test(path))
  50. return path
  51. }
  52. return 'bundle-assets://' + path
  53. }
  54. function createFile(path:string, data:string, encoding: 'base64' | 'ascii' | 'utf8'):Promise {
  55. encoding = encoding || 'utf8'
  56. return new Promise((resolve, reject) => {
  57. let handler = (err) => {
  58. if(err)
  59. reject(err)
  60. else
  61. resolve()
  62. }
  63. if(encoding.toLowerCase() === 'ascii') {
  64. if(Array.isArray(data))
  65. RNFetchBlob.createFileASCII(path, data, handler)
  66. else
  67. reject('`data` of ASCII file must be an array contains numbers')
  68. }
  69. else {
  70. RNFetchBlob.createFile(path, data, encoding, handler)
  71. }
  72. })
  73. }
  74. /**
  75. * Create write stream to a file.
  76. * @param {string} path Target path of file stream.
  77. * @param {string} encoding Encoding of input data.
  78. * @param {bool} append A flag represent if data append to existing ones.
  79. * @return {Promise<WriteStream>} A promise resolves a `WriteStream` object.
  80. */
  81. function writeStream(
  82. path : string,
  83. encoding : 'utf8' | 'ascii' | 'base64',
  84. append? : ?bool,
  85. ):Promise<RNFetchBlobWriteStream> {
  86. if(!path)
  87. throw Error('RNFetchBlob could not open file stream with empty `path`')
  88. encoding = encoding || 'utf8'
  89. append = append || false
  90. return new Promise((resolve, reject) => {
  91. RNFetchBlob.writeStream(path, encoding || 'base64', append || false, (err, streamId:string) => {
  92. if(err)
  93. reject(err)
  94. else
  95. resolve(new RNFetchBlobWriteStream(streamId, encoding))
  96. })
  97. })
  98. }
  99. /**
  100. * Create file stream from file at `path`.
  101. * @param {string} path The file path.
  102. * @param {string} encoding Data encoding, should be one of `base64`, `utf8`, `ascii`
  103. * @param {boolean} bufferSize Size of stream buffer.
  104. * @return {RNFetchBlobStream} RNFetchBlobStream stream instance.
  105. */
  106. function readStream(
  107. path : string,
  108. encoding : 'utf8' | 'ascii' | 'base64',
  109. bufferSize? : ?number,
  110. tick : ?number = 10
  111. ):Promise<RNFetchBlobReadStream> {
  112. return Promise.resolve(new RNFetchBlobReadStream(path, encoding, bufferSize, tick))
  113. }
  114. /**
  115. * Create a directory.
  116. * @param {string} path Path of directory to be created
  117. * @return {Promise}
  118. */
  119. function mkdir(path:string):Promise {
  120. return new Promise((resolve, reject) => {
  121. RNFetchBlob.mkdir(path, (err, res) => {
  122. if(err)
  123. reject(err)
  124. else
  125. resolve()
  126. })
  127. })
  128. }
  129. /**
  130. * Wrapper method of readStream.
  131. * @param {string} path Path of the file.
  132. * @param {'base64' | 'utf8' | 'ascii'} encoding Encoding of read stream.
  133. * @return {Promise<Array<number> | string>}
  134. */
  135. function readFile(path:string, encoding:string, bufferSize:?number):Promise<any> {
  136. if(typeof path !== 'string')
  137. return Promise.reject('Invalid argument "path" ')
  138. return RNFetchBlob.readFile(path, encoding)
  139. }
  140. /**
  141. * Write data to file.
  142. * @param {string} path Path of the file.
  143. * @param {string | number[]} data Data to write to the file.
  144. * @param {string} encoding Encoding of data (Optional).
  145. * @return {Promise}
  146. */
  147. function writeFile(path:string, data:string | Array<number>, encoding:?string):Promise {
  148. encoding = encoding || 'utf8'
  149. if(typeof path !== 'string')
  150. return Promise.reject('Invalid argument "path" ')
  151. if(encoding.toLocaleLowerCase() === 'ascii') {
  152. if(!Array.isArray(data))
  153. Promise.reject(`Expected "data" is an Array when encoding is "ascii", however got ${typeof data}`)
  154. else
  155. return RNFetchBlob.writeFileArray(path, data, false);
  156. } else {
  157. if(typeof data !== 'string')
  158. Promise.reject(`Expected "data" is a String when encoding is "utf8" or "base64", however got ${typeof data}`)
  159. else
  160. return RNFetchBlob.writeFile(path, encoding, data, false);
  161. }
  162. }
  163. function appendFile(path:string, data:string | Array<number>, encoding:?string):Promise {
  164. encoding = encoding || 'utf8'
  165. if(typeof path !== 'string')
  166. return Promise.reject('Invalid argument "path" ')
  167. if(encoding.toLocaleLowerCase() === 'ascii') {
  168. if(!Array.isArray(data))
  169. Promise.reject(`Expected "data" is an Array when encoding is "ascii", however got ${typeof data}`)
  170. else
  171. return RNFetchBlob.writeFileArray(path, data, true);
  172. } else {
  173. if(typeof data !== 'string')
  174. Promise.reject(`Expected "data" is a String when encoding is "utf8" or "base64", however got ${typeof data}`)
  175. else
  176. return RNFetchBlob.writeFile(path, encoding, data, true);
  177. }
  178. }
  179. /**
  180. * Show statistic data of a path.
  181. * @param {string} path Target path
  182. * @return {RNFetchBlobFile}
  183. */
  184. function stat(path:string):Promise<RNFetchBlobFile> {
  185. return new Promise((resolve, reject) => {
  186. RNFetchBlob.stat(path, (err, stat) => {
  187. if(err)
  188. reject(err)
  189. else
  190. resolve(stat)
  191. })
  192. })
  193. }
  194. /**
  195. * Android only method, request media scanner to scan the file.
  196. * @param {Array<Object<string, string>>} Array contains Key value pairs with key `path` and `mime`.
  197. * @return {Promise}
  198. */
  199. function scanFile(pairs:any):Promise {
  200. return new Promise((resolve, reject) => {
  201. RNFetchBlob.scanFile(pairs, (err) => {
  202. if(err)
  203. reject(err)
  204. else
  205. resolve()
  206. })
  207. })
  208. }
  209. function cp(path:string, dest:string):Promise<boolean> {
  210. return new Promise((resolve, reject) => {
  211. RNFetchBlob.cp(path, dest, (err, res) => {
  212. if(err)
  213. reject(err)
  214. else
  215. resolve(res)
  216. })
  217. })
  218. }
  219. function mv(path:string, dest:string):Promise<boolean> {
  220. return new Promise((resolve, reject) => {
  221. RNFetchBlob.mv(path, dest, (err, res) => {
  222. if(err)
  223. reject(err)
  224. else
  225. resolve(res)
  226. })
  227. })
  228. }
  229. function lstat(path:string):Promise<Array<RNFetchBlobFile>> {
  230. return new Promise((resolve, reject) => {
  231. RNFetchBlob.lstat(path, (err, stat) => {
  232. if(err)
  233. reject(err)
  234. else
  235. resolve(stat)
  236. })
  237. })
  238. }
  239. function ls(path:string):Promise<Array<String>> {
  240. return new Promise((resolve, reject) => {
  241. RNFetchBlob.ls(path, (err, res) => {
  242. if(err)
  243. reject(err)
  244. else
  245. resolve(res)
  246. })
  247. })
  248. }
  249. /**
  250. * Remove file at path.
  251. * @param {string} path:string Path of target file.
  252. * @return {Promise}
  253. */
  254. function unlink(path:string):Promise {
  255. return new Promise((resolve, reject) => {
  256. RNFetchBlob.unlink(path, (err) => {
  257. if(err)
  258. reject(err)
  259. else
  260. resolve()
  261. })
  262. })
  263. }
  264. /**
  265. * Check if file exists and if it is a folder.
  266. * @param {string} path Path to check
  267. * @return {Promise<bool, bool>}
  268. */
  269. function exists(path:string):Promise<bool, bool> {
  270. return new Promise((resolve, reject) => {
  271. try {
  272. RNFetchBlob.exists(path, (exist) => {
  273. resolve(exist)
  274. })
  275. } catch(err) {
  276. reject(err)
  277. }
  278. })
  279. }
  280. function slice(src:string, dest:string, start:number, end:number):Promise {
  281. let p = Promise.resolve()
  282. let size = 0
  283. function normalize(num, size) {
  284. if(num < 0)
  285. return Math.max(0, size + num)
  286. if(!num && num !== 0)
  287. return size
  288. return num
  289. }
  290. if(start < 0 || end < 0 || !start || !end) {
  291. p = p.then(() => stat(src))
  292. .then((stat) => {
  293. size = Math.floor(stat.size)
  294. start = normalize(start || 0, size)
  295. end = normalize(end, size)
  296. return Promise.resolve()
  297. })
  298. }
  299. return p.then(() => RNFetchBlob.slice(src, dest, start, end))
  300. }
  301. function isDir(path:string):Promise<bool, bool> {
  302. return new Promise((resolve, reject) => {
  303. try {
  304. RNFetchBlob.exists(path, (exist, isDir) => {
  305. resolve(isDir)
  306. })
  307. } catch(err) {
  308. reject(err)
  309. }
  310. })
  311. }
  312. export default {
  313. RNFetchBlobSession,
  314. unlink,
  315. mkdir,
  316. session,
  317. ls,
  318. readStream,
  319. mv,
  320. cp,
  321. writeStream,
  322. writeFile,
  323. appendFile,
  324. readFile,
  325. exists,
  326. createFile,
  327. isDir,
  328. stat,
  329. lstat,
  330. scanFile,
  331. dirs,
  332. slice,
  333. asset
  334. }