No Description

fs.js 12KB

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