No Description

fs.js 11KB

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