No Description

fs.js 10KB

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