Aucune description

fs.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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,
  20. SDCardApplicationDir: RNFetchBlob.SDCardApplicationDir,
  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. * Wrapper method of readStream.
  127. * @param {string} path Path of the file.
  128. * @param {'base64' | 'utf8' | 'ascii'} encoding Encoding of read stream.
  129. * @return {Promise<Array<number> | string>}
  130. */
  131. function readFile(path: string, encoding: string = 'utf8'): Promise<any> {
  132. if (typeof path !== 'string') {
  133. return Promise.reject(addCode('EINVAL', new TypeError('Missing argument "path" ')))
  134. }
  135. return RNFetchBlob.readFile(path, encoding)
  136. }
  137. /**
  138. * Write data to file.
  139. * @param {string} path Path of the file.
  140. * @param {string | number[]} data Data to write to the file.
  141. * @param {string} encoding Encoding of data (Optional).
  142. * @return {Promise}
  143. */
  144. function writeFile(path: string, data: string | Array<number>, encoding: ?string = 'utf8'): Promise {
  145. if (typeof path !== 'string') {
  146. return Promise.reject(addCode('EINVAL', new TypeError('Missing argument "path" ')))
  147. }
  148. if (encoding.toLocaleLowerCase() === 'ascii') {
  149. if (!Array.isArray(data)) {
  150. return Promise.reject(addCode('EINVAL', new TypeError('"data" must be an Array when encoding is "ascii"')))
  151. }
  152. else
  153. return RNFetchBlob.writeFileArray(path, data, false)
  154. }
  155. else {
  156. if (typeof data !== 'string') {
  157. return Promise.reject(addCode('EINVAL', new TypeError(`"data" must be a String when encoding is "utf8" or "base64", but it is "${typeof data}"`)))
  158. }
  159. else
  160. return RNFetchBlob.writeFile(path, encoding, data, false)
  161. }
  162. }
  163. function appendFile(path: string, data: string | Array<number>, encoding?: string = 'utf8'): Promise<number> {
  164. if (typeof path !== 'string') {
  165. return Promise.reject(addCode('EINVAL', new TypeError('Missing argument "path" ')))
  166. }
  167. if (encoding.toLocaleLowerCase() === 'ascii') {
  168. if (!Array.isArray(data)) {
  169. return Promise.reject(addCode('EINVAL', new TypeError('`data` of ASCII file must be an array with 0..255 numbers')))
  170. }
  171. else
  172. return RNFetchBlob.writeFileArray(path, data, true)
  173. }
  174. else {
  175. if (typeof data !== 'string') {
  176. return Promise.reject(addCode('EINVAL'), new TypeError(`"data" must be a String when encoding is "utf8" or "base64", but it is "${typeof data}"`))
  177. }
  178. else
  179. return RNFetchBlob.writeFile(path, encoding, data, true)
  180. }
  181. }
  182. /**
  183. * Show statistic data of a path.
  184. * @param {string} path Target path
  185. * @return {RNFetchBlobFile}
  186. */
  187. function stat(path: string): Promise<RNFetchBlobFile> {
  188. return new Promise((resolve, reject) => {
  189. if (typeof path !== 'string') {
  190. return reject(addCode('EINVAL', new TypeError('Missing argument "path" ')))
  191. }
  192. RNFetchBlob.stat(path, (err, stat) => {
  193. if (err)
  194. reject(new Error(err))
  195. else {
  196. if (stat) {
  197. stat.size = parseInt(stat.size)
  198. stat.lastModified = parseInt(stat.lastModified)
  199. }
  200. resolve(stat)
  201. }
  202. })
  203. })
  204. }
  205. /**
  206. * Android only method, request media scanner to scan the file.
  207. * @param {Array<Object<string, string>>} pairs Array contains Key value pairs with key `path` and `mime`.
  208. * @return {Promise}
  209. */
  210. function scanFile(pairs: any): Promise {
  211. return new Promise((resolve, reject) => {
  212. if (pairs === undefined) {
  213. return reject(addCode('EINVAL', new TypeError('Missing argument')))
  214. }
  215. RNFetchBlob.scanFile(pairs, (err) => {
  216. if (err)
  217. reject(addCode('EUNSPECIFIED', new Error(err)))
  218. else
  219. resolve()
  220. })
  221. })
  222. }
  223. function hash(path: string, algorithm: string): Promise<string> {
  224. if (typeof path !== 'string' || typeof algorithm !== 'string') {
  225. return Promise.reject(addCode('EINVAL', new TypeError('Missing argument "path" and/or "algorithm"')))
  226. }
  227. return RNFetchBlob.hash(path, algorithm)
  228. }
  229. function cp(path: string, dest: string): Promise<boolean> {
  230. return new Promise((resolve, reject) => {
  231. if (typeof path !== 'string' || typeof dest !== 'string') {
  232. return reject(addCode('EINVAL', new TypeError('Missing argument "path" and/or "destination"')))
  233. }
  234. RNFetchBlob.cp(path, dest, (err, res) => {
  235. if (err)
  236. reject(addCode('EUNSPECIFIED', new Error(err)))
  237. else
  238. resolve(res)
  239. })
  240. })
  241. }
  242. function mv(path: string, dest: string): Promise<boolean> {
  243. return new Promise((resolve, reject) => {
  244. if (typeof path !== 'string' || typeof dest !== 'string') {
  245. return reject(addCode('EINVAL', new TypeError('Missing argument "path" and/or "destination"')))
  246. }
  247. RNFetchBlob.mv(path, dest, (err, res) => {
  248. if (err)
  249. reject(addCode('EUNSPECIFIED', new Error(err)))
  250. else
  251. resolve(res)
  252. })
  253. })
  254. }
  255. function lstat(path: string): Promise<Array<RNFetchBlobFile>> {
  256. return new Promise((resolve, reject) => {
  257. if (typeof path !== 'string') {
  258. return reject(addCode('EINVAL', new TypeError('Missing argument "path" ')))
  259. }
  260. RNFetchBlob.lstat(path, (err, stat) => {
  261. if (err)
  262. reject(addCode('EUNSPECIFIED', new Error(err)))
  263. else
  264. resolve(stat)
  265. })
  266. })
  267. }
  268. function ls(path: string): Promise<Array<String>> {
  269. if (typeof path !== 'string') {
  270. return Promise.reject(addCode('EINVAL', new TypeError('Missing argument "path" ')))
  271. }
  272. return RNFetchBlob.ls(path)
  273. }
  274. /**
  275. * Remove file at path.
  276. * @param {string} path:string Path of target file.
  277. * @return {Promise}
  278. */
  279. function unlink(path: string): Promise {
  280. return new Promise((resolve, reject) => {
  281. if (typeof path !== 'string') {
  282. return reject(addCode('EINVAL', new TypeError('Missing argument "path" ')))
  283. }
  284. RNFetchBlob.unlink(path, (err) => {
  285. if (err) {
  286. reject(addCode('EUNSPECIFIED', new Error(err)))
  287. }
  288. else
  289. resolve()
  290. })
  291. })
  292. }
  293. /**
  294. * Check if file exists and if it is a folder.
  295. * @param {string} path Path to check
  296. * @return {Promise<boolean>}
  297. */
  298. function exists(path: string): Promise<boolean> {
  299. return new Promise((resolve, reject) => {
  300. if (typeof path !== 'string') {
  301. return reject(addCode('EINVAL', new TypeError('Missing argument "path" ')))
  302. }
  303. try {
  304. RNFetchBlob.exists(path, (exist) => {
  305. resolve(exist)
  306. })
  307. }catch (err){
  308. reject(addCode('EUNSPECIFIED', new Error(err)))
  309. }
  310. })
  311. }
  312. function slice(src: string, dest: string, start: number, end: number): Promise {
  313. if (typeof src !== 'string' || typeof dest !== 'string') {
  314. return reject(addCode('EINVAL', new TypeError('Missing argument "src" and/or "destination"')))
  315. }
  316. let p = Promise.resolve()
  317. let size = 0
  318. function normalize(num, size) {
  319. if (num < 0)
  320. return Math.max(0, size + num)
  321. if (!num && num !== 0)
  322. return size
  323. return num
  324. }
  325. if (start < 0 || end < 0 || !start || !end) {
  326. p = p.then(() => stat(src))
  327. .then((stat) => {
  328. size = Math.floor(stat.size)
  329. start = normalize(start || 0, size)
  330. end = normalize(end, size)
  331. })
  332. }
  333. return p.then(() => RNFetchBlob.slice(src, dest, start, end))
  334. }
  335. function isDir(path: string): Promise<bool> {
  336. return new Promise((resolve, reject) => {
  337. if (typeof path !== 'string') {
  338. return reject(addCode('EINVAL', new TypeError('Missing argument "path" ')))
  339. }
  340. try {
  341. RNFetchBlob.exists(path, (exist, isDir) => {
  342. resolve(isDir)
  343. })
  344. }catch (err){
  345. reject(addCode('EUNSPECIFIED', new Error(err)))
  346. }
  347. })
  348. }
  349. function df(): Promise<{ free: number, total: number }> {
  350. return new Promise((resolve, reject) => {
  351. RNFetchBlob.df((err, stat) => {
  352. if (err)
  353. reject(addCode('EUNSPECIFIED', new Error(err)))
  354. else
  355. resolve(stat)
  356. })
  357. })
  358. }
  359. export default {
  360. RNFetchBlobSession,
  361. unlink,
  362. mkdir,
  363. session,
  364. ls,
  365. readStream,
  366. mv,
  367. cp,
  368. writeStream,
  369. writeFile,
  370. appendFile,
  371. pathForAppGroup,
  372. readFile,
  373. hash,
  374. exists,
  375. createFile,
  376. isDir,
  377. stat,
  378. lstat,
  379. scanFile,
  380. dirs,
  381. slice,
  382. asset,
  383. df
  384. }