No Description

fs.js 9.6KB

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