No Description

fs.js 12KB

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