Browse Source

Fix for issue #468, #461, #460 and minor cleanup (#469)

* bump to 0.10.8

* Update PULL_REQUEST_TEMPLATE

* Fix #468 "Messy error returns: Sometimes a string, sometimes an Error object"

* Cleanup: remove an unused constant and duplicate method definitions

* Cleanup:
- fix minor errors in JSDoc comments, for example {string]} => {string}
- fix parameter name "encode" => "encoding" (more logical, and it says so in the function's JSDoc too)
- json-stream.js: split a looooong log message string constant into two parts and fix a typo ("maually"), and the type for objects is "Object" (capitalized) in Flow type annotations

* Fix a (Flow) type conflict - fixes issue #461

* NEEDS REVIEW - Attempt to fix some of issue #460 (Error message normalization)

Error messages reported by iOS and Android versions should be as similar as possible. Also, within the same system there should be consistency. This patch is an attempt to bring a LITTLE more of this consistency to the error messages. I also fixed some very few minor language issues, like "does not exist" (is the correct English). I tried keeping the changes to a minimum.

Background: In my project code I want to know when a file already exists (e.g. after calling fs.createFile), and the only way is to check the error message string that I get. It's bad if they differ between versions (createFileASCII and createFile) and then also between Android and iOS version. At least some core part of the string should be the same, so that I have something to match.

Ideally messages should come from a centralized easy (easier) to maintain file (for both iOS and Android), and ideally both systems should have the same errors and messages as far as possible.
KittenWithHerbs 7 years ago
parent
commit
b6344023a0

+ 1
- 1
.github/PULL_REQUEST_TEMPLATE View File

1
 Thank you for making a pull request ! Just a gentle reminder :)
1
 Thank you for making a pull request ! Just a gentle reminder :)
2
 
2
 
3
 1. If the PR is offering a feature please make the request to our "Feature Branch" 0.11.0
3
 1. If the PR is offering a feature please make the request to our "Feature Branch" 0.11.0
4
-2. Bug fix request to "Bug Fix Branch" 0.10.8
4
+2. Bug fix request to "Bug Fix Branch" 0.10.9
5
 3. Correct README.md can directly to master
5
 3. Correct README.md can directly to master

+ 1
- 1
android.js View File

13
 
13
 
14
 /**
14
 /**
15
  * Send an intent to open the file.
15
  * Send an intent to open the file.
16
- * @param  {string]} path Path of the file to be open.
16
+ * @param  {string} path Path of the file to be open.
17
  * @param  {string} mime MIME type string
17
  * @param  {string} mime MIME type string
18
  * @return {Promise}
18
  * @return {Promise}
19
  */
19
  */

+ 27
- 24
android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java View File

78
                 data = normalizePath(data);
78
                 data = normalizePath(data);
79
                 File src = new File(data);
79
                 File src = new File(data);
80
                 if(!src.exists()) {
80
                 if(!src.exists()) {
81
-                    promise.reject("RNfetchBlob writeFileError", "source file : " + data + "not exists");
81
+                    promise.reject("RNfetchBlob writeFile error", "source file : " + data + " does not exist");
82
                     fout.close();
82
                     fout.close();
83
                     return ;
83
                     return ;
84
                 }
84
                 }
100
             fout.close();
100
             fout.close();
101
             promise.resolve(written);
101
             promise.resolve(written);
102
         } catch (Exception e) {
102
         } catch (Exception e) {
103
-            promise.reject("RNFetchBlob writeFileError", e.getLocalizedMessage());
103
+            promise.reject("RNFetchBlob writeFile error", e.getLocalizedMessage());
104
         }
104
         }
105
     }
105
     }
106
 
106
 
127
             os.close();
127
             os.close();
128
             promise.resolve(data.size());
128
             promise.resolve(data.size());
129
         } catch (Exception e) {
129
         } catch (Exception e) {
130
-            promise.reject("RNFetchBlob writeFileError", e.getLocalizedMessage());
130
+            promise.reject("RNFetchBlob writeFile error", e.getLocalizedMessage());
131
         }
131
         }
132
     }
132
     }
133
 
133
 
309
             buffer = null;
309
             buffer = null;
310
 
310
 
311
         } catch (Exception err) {
311
         } catch (Exception err) {
312
-            emitStreamEvent(streamId, "warn", "Failed to convert data to "+encoding+" encoded string, this might due to the source data is not able to convert using this encoding.");
312
+            emitStreamEvent(streamId, "warn", "Failed to convert data to " + encoding +
313
+                    " encoded string, this might due to the source data is not able to convert using this encoding.");
313
             err.printStackTrace();
314
             err.printStackTrace();
314
         }
315
         }
315
     }
316
     }
324
     public void writeStream(String path, String encoding, boolean append, Callback callback) {
325
     public void writeStream(String path, String encoding, boolean append, Callback callback) {
325
         File dest = new File(path);
326
         File dest = new File(path);
326
         if(!dest.exists() || dest.isDirectory()) {
327
         if(!dest.exists() || dest.isDirectory()) {
327
-            callback.invoke("write stream error: target path `" + path + "` may not exists or it's a folder");
328
+            callback.invoke("target path `" + path + "` may not exist or it is a folder");
328
             return;
329
             return;
329
         }
330
         }
330
         try {
331
         try {
336
             this.writeStreamInstance = fs;
337
             this.writeStreamInstance = fs;
337
             callback.invoke(null, streamId);
338
             callback.invoke(null, streamId);
338
         } catch(Exception err) {
339
         } catch(Exception err) {
339
-            callback.invoke("write stream error: failed to create write stream at path `"+path+"` "+ err.getLocalizedMessage());
340
+            callback.invoke("failed to create write stream at path `" + path + "` " + err.getLocalizedMessage());
340
         }
341
         }
341
 
342
 
342
     }
343
     }
433
     static void mkdir(String path, Callback callback) {
434
     static void mkdir(String path, Callback callback) {
434
         File dest = new File(path);
435
         File dest = new File(path);
435
         if(dest.exists()) {
436
         if(dest.exists()) {
436
-            callback.invoke("mkdir error: failed to create folder at `" + path + "` folder already exists");
437
+            callback.invoke("mkdir failed, folder already exists at " + path);
437
             return;
438
             return;
438
         }
439
         }
439
         dest.mkdirs();
440
         dest.mkdirs();
440
         callback.invoke();
441
         callback.invoke();
441
     }
442
     }
443
+
442
     /**
444
     /**
443
      * Copy file to destination path
445
      * Copy file to destination path
444
      * @param path Source path
446
      * @param path Source path
454
         try {
456
         try {
455
 
457
 
456
             if(!isPathExists(path)) {
458
             if(!isPathExists(path)) {
457
-                callback.invoke("cp error: source file at path`" + path + "` not exists");
459
+                callback.invoke("source file at path`" + path + "` does not exist");
458
                 return;
460
                 return;
459
             }
461
             }
460
             if(!new File(dest).exists())
462
             if(!new File(dest).exists())
495
     static void mv(String path, String dest, Callback callback) {
497
     static void mv(String path, String dest, Callback callback) {
496
         File src = new File(path);
498
         File src = new File(path);
497
         if(!src.exists()) {
499
         if(!src.exists()) {
498
-            callback.invoke("mv error: source file at path `" + path + "` does not exists");
500
+            callback.invoke("source file at path `" + path + "` does not exist");
499
             return;
501
             return;
500
         }
502
         }
501
         src.renameTo(new File(dest));
503
         src.renameTo(new File(dest));
535
         path = normalizePath(path);
537
         path = normalizePath(path);
536
         File src = new File(path);
538
         File src = new File(path);
537
         if (!src.exists() || !src.isDirectory()) {
539
         if (!src.exists() || !src.isDirectory()) {
538
-            callback.invoke("ls error: failed to list path `" + path + "` for it is not exist or it is not a folder");
540
+            callback.invoke("failed to list path `" + path + "` for it is not exist or it is not a folder");
539
             return;
541
             return;
540
         }
542
         }
541
         String[] files = new File(path).list();
543
         String[] files = new File(path).list();
559
             src = normalizePath(src);
561
             src = normalizePath(src);
560
             File source = new File(src);
562
             File source = new File(src);
561
             if(!source.exists()) {
563
             if(!source.exists()) {
562
-                promise.reject("RNFetchBlob.slice error", "source file : " + src + " not exists");
564
+                promise.reject("RNFetchBlob slice error", "source file : " + src + " does not exist");
563
                 return;
565
                 return;
564
             }
566
             }
565
             long size = source.length();
567
             long size = source.length();
585
             promise.resolve(dest);
587
             promise.resolve(dest);
586
         } catch (Exception e) {
588
         } catch (Exception e) {
587
             e.printStackTrace();
589
             e.printStackTrace();
588
-            promise.reject(e.getLocalizedMessage());
590
+            promise.reject("RNFetchBlob slice error", e.getLocalizedMessage());
589
         }
591
         }
590
     }
592
     }
591
 
593
 
597
             protected Integer doInBackground(String ...args) {
599
             protected Integer doInBackground(String ...args) {
598
                 WritableArray res = Arguments.createArray();
600
                 WritableArray res = Arguments.createArray();
599
                 if(args[0] == null) {
601
                 if(args[0] == null) {
600
-                    callback.invoke("lstat error: the path specified for lstat is either `null` or `undefined`.");
602
+                    callback.invoke("the path specified for lstat is either `null` or `undefined`.");
601
                     return 0;
603
                     return 0;
602
                 }
604
                 }
603
                 File src = new File(args[0]);
605
                 File src = new File(args[0]);
604
                 if(!src.exists()) {
606
                 if(!src.exists()) {
605
-                    callback.invoke("lstat error: failed to list path `" + args[0] + "` for it is not exist or it is not a folder");
607
+                    callback.invoke("failed to lstat path `" + args[0] + "` because it does not exist or it is not a folder");
606
                     return 0;
608
                     return 0;
607
                 }
609
                 }
608
                 if(src.isDirectory()) {
610
                 if(src.isDirectory()) {
609
                     String [] files = src.list();
611
                     String [] files = src.list();
610
                     for(String p : files) {
612
                     for(String p : files) {
611
-                        res.pushMap(statFile ( src.getPath() + "/" + p));
613
+                        res.pushMap(statFile(src.getPath() + "/" + p));
612
                     }
614
                     }
613
                 }
615
                 }
614
                 else {
616
                 else {
630
             path = normalizePath(path);
632
             path = normalizePath(path);
631
             WritableMap result = statFile(path);
633
             WritableMap result = statFile(path);
632
             if(result == null)
634
             if(result == null)
633
-                callback.invoke("stat error: failed to list path `" + path + "` for it is not exist or it is not a folder", null);
635
+                callback.invoke("failed to stat path `" + path + "` because it does not exist or it is not a folder", null);
634
             else
636
             else
635
                 callback.invoke(null, result);
637
                 callback.invoke(null, result);
636
         } catch(Exception err) {
638
         } catch(Exception err) {
709
                 String orgPath = data.replace(RNFetchBlobConst.FILE_PREFIX, "");
711
                 String orgPath = data.replace(RNFetchBlobConst.FILE_PREFIX, "");
710
                 File src = new File(orgPath);
712
                 File src = new File(orgPath);
711
                 if(!src.exists()) {
713
                 if(!src.exists()) {
712
-                    callback.invoke("RNfetchBlob writeFileError", "source file : " + data + "not exists");
714
+                    callback.invoke("source file : " + data + " does not exist");
713
                     return ;
715
                     return ;
714
                 }
716
                 }
715
                 FileInputStream fin = new FileInputStream(src);
717
                 FileInputStream fin = new FileInputStream(src);
716
                 OutputStream ostream = new FileOutputStream(dest);
718
                 OutputStream ostream = new FileOutputStream(dest);
717
-                byte [] buffer = new byte [10240];
719
+                byte[] buffer = new byte[10240];
718
                 int read = fin.read(buffer);
720
                 int read = fin.read(buffer);
719
-                while(read > 0) {
721
+                while (read > 0) {
720
                     ostream.write(buffer, 0, read);
722
                     ostream.write(buffer, 0, read);
721
                     read = fin.read(buffer);
723
                     read = fin.read(buffer);
722
                 }
724
                 }
723
                 fin.close();
725
                 fin.close();
724
                 ostream.close();
726
                 ostream.close();
725
-            }
726
-            else {
727
+            } else {
727
                 if (!created) {
728
                 if (!created) {
728
-                    callback.invoke("create file error: failed to create file at path `" + path + "` for its parent path may not exists, or the file already exists. If you intended to overwrite the existing file use fs.writeFile instead.");
729
+                    callback.invoke("failed to create new file at path `" + path + "` because its parent path " +
730
+                            "may not exist, or the file already exists. If you intended to overwrite the " +
731
+                            "existing file use fs.writeFile instead.");
729
                     return;
732
                     return;
730
                 }
733
                 }
731
                 OutputStream ostream = new FileOutputStream(dest);
734
                 OutputStream ostream = new FileOutputStream(dest);
747
         try {
750
         try {
748
             File dest = new File(path);
751
             File dest = new File(path);
749
             if(dest.exists()) {
752
             if(dest.exists()) {
750
-                callback.invoke("create file error: failed to create file at path `" + path + "`, file already exists.");
753
+                callback.invoke("failed to create new file at path `" + path + "`, file already exists.");
751
                 return;
754
                 return;
752
             }
755
             }
753
             boolean created = dest.createNewFile();
756
             boolean created = dest.createNewFile();
754
             if(!created) {
757
             if(!created) {
755
-                callback.invoke("create file error: failed to create file at path `" + path + "` for its parent path may not exists");
758
+                callback.invoke("failed to create new file at path `" + path + "` because its parent path may not exist");
756
                 return;
759
                 return;
757
             }
760
             }
758
             OutputStream ostream = new FileOutputStream(dest);
761
             OutputStream ostream = new FileOutputStream(dest);

+ 2
- 7
class/RNFetchBlobSession.js View File

9
 } from 'react-native'
9
 } from 'react-native'
10
 
10
 
11
 const RNFetchBlob = NativeModules.RNFetchBlob
11
 const RNFetchBlob = NativeModules.RNFetchBlob
12
-const emitter = DeviceEventEmitter
13
 
12
 
14
 let sessions = {}
13
 let sessions = {}
15
 
14
 
16
 export default class RNFetchBlobSession {
15
 export default class RNFetchBlobSession {
17
 
16
 
18
-  add : (path:string) => RNFetchBlobSession;
19
-  remove : (path:string) => RNFetchBlobSession;
20
-  dispose : () => Promise;
21
-  list : () => Array<string>;
22
   name : string;
17
   name : string;
23
 
18
 
24
   static getSession(name:string):any {
19
   static getSession(name:string):any {
50
 
45
 
51
   remove(path:string):RNFetchBlobSession {
46
   remove(path:string):RNFetchBlobSession {
52
     let list = sessions[this.name]
47
     let list = sessions[this.name]
53
-    for(let i in list) {
48
+    for(let i of list) {
54
       if(list[i] === path) {
49
       if(list[i] === path) {
55
         sessions[this.name].splice(i, 1)
50
         sessions[this.name].splice(i, 1)
56
         break;
51
         break;
67
     return new Promise((resolve, reject) => {
62
     return new Promise((resolve, reject) => {
68
       RNFetchBlob.removeSession(sessions[this.name], (err) => {
63
       RNFetchBlob.removeSession(sessions[this.name], (err) => {
69
         if(err)
64
         if(err)
70
-          reject(err)
65
+          reject(new Error(err))
71
         else {
66
         else {
72
           delete sessions[this.name]
67
           delete sessions[this.name]
73
           resolve()
68
           resolve()

+ 6
- 7
class/RNFetchBlobWriteStream.js View File

9
 } from 'react-native'
9
 } from 'react-native'
10
 
10
 
11
 const RNFetchBlob = NativeModules.RNFetchBlob
11
 const RNFetchBlob = NativeModules.RNFetchBlob
12
-const emitter = DeviceEventEmitter
13
 
12
 
14
 export default class RNFetchBlobWriteStream {
13
 export default class RNFetchBlobWriteStream {
15
 
14
 
16
   id : string;
15
   id : string;
17
   encoding : string;
16
   encoding : string;
18
-  append : bool;
17
+  append : boolean;
19
 
18
 
20
-  constructor(streamId:string, encoding:string, append:string) {
19
+  constructor(streamId:string, encoding:string, append:boolean) {
21
     this.id = streamId
20
     this.id = streamId
22
     this.encoding = encoding
21
     this.encoding = encoding
23
     this.append = append
22
     this.append = append
28
       try {
27
       try {
29
         let method = this.encoding === 'ascii' ? 'writeArrayChunk' : 'writeChunk'
28
         let method = this.encoding === 'ascii' ? 'writeArrayChunk' : 'writeChunk'
30
         if(this.encoding.toLocaleLowerCase() === 'ascii' && !Array.isArray(data)) {
29
         if(this.encoding.toLocaleLowerCase() === 'ascii' && !Array.isArray(data)) {
31
-            reject('ascii input data must be an Array')
30
+            reject(new Error('ascii input data must be an Array'))
32
             return
31
             return
33
         }
32
         }
34
         RNFetchBlob[method](this.id, data, (error) => {
33
         RNFetchBlob[method](this.id, data, (error) => {
35
           if(error)
34
           if(error)
36
-            reject(error)
35
+            reject(new Error(error))
37
           else
36
           else
38
             resolve()
37
             resolve()
39
         })
38
         })
40
       } catch(err) {
39
       } catch(err) {
41
-        reject(err)
40
+        reject(new Error(err))
42
       }
41
       }
43
     })
42
     })
44
   }
43
   }
50
           resolve()
49
           resolve()
51
         })
50
         })
52
       } catch (err) {
51
       } catch (err) {
53
-        reject(err)
52
+        reject(new Error(err))
54
       }
53
       }
55
     })
54
     })
56
   }
55
   }

+ 12
- 12
fs.js View File

19
 } from './types'
19
 } from './types'
20
 
20
 
21
 const RNFetchBlob:RNFetchBlobNative = NativeModules.RNFetchBlob
21
 const RNFetchBlob:RNFetchBlobNative = NativeModules.RNFetchBlob
22
-const emitter = DeviceEventEmitter
22
+
23
 const dirs = {
23
 const dirs = {
24
     DocumentDir :  RNFetchBlob.DocumentDir,
24
     DocumentDir :  RNFetchBlob.DocumentDir,
25
     CacheDir : RNFetchBlob.CacheDir,
25
     CacheDir : RNFetchBlob.CacheDir,
83
  * Create write stream to a file.
83
  * Create write stream to a file.
84
  * @param  {string} path Target path of file stream.
84
  * @param  {string} path Target path of file stream.
85
  * @param  {string} encoding Encoding of input data.
85
  * @param  {string} encoding Encoding of input data.
86
- * @param  {bool} append  A flag represent if data append to existing ones.
87
- * @return {Promise<WriteStream>} A promise resolves a `WriteStream` object.
86
+ * @param  {boolean} [append]  A flag represent if data append to existing ones.
87
+ * @return {Promise<RNFetchBlobWriteStream>} A promise resolves a `WriteStream` object.
88
  */
88
  */
89
 function writeStream(
89
 function writeStream(
90
   path : string,
90
   path : string,
91
   encoding : 'utf8' | 'ascii' | 'base64',
91
   encoding : 'utf8' | 'ascii' | 'base64',
92
-  append? : ?bool,
92
+  append? : ?boolean,
93
 ):Promise<RNFetchBlobWriteStream> {
93
 ):Promise<RNFetchBlobWriteStream> {
94
   if(!path)
94
   if(!path)
95
     throw Error('RNFetchBlob could not open file stream with empty `path`')
95
     throw Error('RNFetchBlob could not open file stream with empty `path`')
110
  * @param  {string} path   The file path.
110
  * @param  {string} path   The file path.
111
  * @param  {string} encoding Data encoding, should be one of `base64`, `utf8`, `ascii`
111
  * @param  {string} encoding Data encoding, should be one of `base64`, `utf8`, `ascii`
112
  * @param  {boolean} bufferSize Size of stream buffer.
112
  * @param  {boolean} bufferSize Size of stream buffer.
113
+ * @param  {number} [tick=10] Interval in milliseconds between reading chunks of data
113
  * @return {RNFetchBlobStream} RNFetchBlobStream stream instance.
114
  * @return {RNFetchBlobStream} RNFetchBlobStream stream instance.
114
  */
115
  */
115
 function readStream(
116
 function readStream(
154
  * @param  {'base64' | 'utf8' | 'ascii'} encoding Encoding of read stream.
155
  * @param  {'base64' | 'utf8' | 'ascii'} encoding Encoding of read stream.
155
  * @return {Promise<Array<number> | string>}
156
  * @return {Promise<Array<number> | string>}
156
  */
157
  */
157
-function readFile(path:string, encoding:string, bufferSize:?number):Promise<any> {
158
+function readFile(path:string, encoding:string):Promise<any> {
158
   if(typeof path !== 'string')
159
   if(typeof path !== 'string')
159
     return Promise.reject(new Error('Invalid argument "path" '))
160
     return Promise.reject(new Error('Invalid argument "path" '))
160
   return RNFetchBlob.readFile(path, encoding)
161
   return RNFetchBlob.readFile(path, encoding)
170
 function writeFile(path:string, data:string | Array<number>, encoding:?string):Promise {
171
 function writeFile(path:string, data:string | Array<number>, encoding:?string):Promise {
171
   encoding = encoding || 'utf8'
172
   encoding = encoding || 'utf8'
172
   if(typeof path !== 'string')
173
   if(typeof path !== 'string')
173
-    return Promise.reject('Invalid argument "path" ')
174
+    return Promise.reject(new Error('Invalid argument "path" '))
174
   if(encoding.toLocaleLowerCase() === 'ascii') {
175
   if(encoding.toLocaleLowerCase() === 'ascii') {
175
     if(!Array.isArray(data))
176
     if(!Array.isArray(data))
176
       return Promise.reject(new Error(`Expected "data" is an Array when encoding is "ascii", however got ${typeof data}`))
177
       return Promise.reject(new Error(`Expected "data" is an Array when encoding is "ascii", however got ${typeof data}`))
187
 function appendFile(path:string, data:string | Array<number>, encoding:?string):Promise {
188
 function appendFile(path:string, data:string | Array<number>, encoding:?string):Promise {
188
   encoding = encoding || 'utf8'
189
   encoding = encoding || 'utf8'
189
   if(typeof path !== 'string')
190
   if(typeof path !== 'string')
190
-    return Promise.reject('Invalid argument "path" ')
191
+    return Promise.reject(new Error('Invalid argument "path" '))
191
   if(encoding.toLocaleLowerCase() === 'ascii') {
192
   if(encoding.toLocaleLowerCase() === 'ascii') {
192
     if(!Array.isArray(data))
193
     if(!Array.isArray(data))
193
       return Promise.reject(new Error(`Expected "data" is an Array when encoding is "ascii", however got ${typeof data}`))
194
       return Promise.reject(new Error(`Expected "data" is an Array when encoding is "ascii", however got ${typeof data}`))
224
 
225
 
225
 /**
226
 /**
226
  * Android only method, request media scanner to scan the file.
227
  * Android only method, request media scanner to scan the file.
227
- * @param  {Array<Object<string, string>>} Array contains Key value pairs with key `path` and `mime`.
228
+ * @param  {Array<Object<string, string>>} pairs Array contains Key value pairs with key `path` and `mime`.
228
  * @return {Promise}
229
  * @return {Promise}
229
  */
230
  */
230
 function scanFile(pairs:any):Promise {
231
 function scanFile(pairs:any):Promise {
302
 /**
303
 /**
303
  * Check if file exists and if it is a folder.
304
  * Check if file exists and if it is a folder.
304
  * @param  {string} path Path to check
305
  * @param  {string} path Path to check
305
- * @return {Promise<bool, bool>}
306
+ * @return {Promise<boolean, boolean>}
306
  */
307
  */
307
-function exists(path:string):Promise<bool, bool> {
308
-
308
+function exists(path:string):Promise<boolean, boolean> {
309
   return new Promise((resolve, reject) => {
309
   return new Promise((resolve, reject) => {
310
     try {
310
     try {
311
       RNFetchBlob.exists(path, (exist) => {
311
       RNFetchBlob.exists(path, (exist) => {
358
   return new Promise((resolve, reject) => {
358
   return new Promise((resolve, reject) => {
359
     RNFetchBlob.df((err, stat) => {
359
     RNFetchBlob.df((err, stat) => {
360
       if(err)
360
       if(err)
361
-        reject(err)
361
+        reject(new Error(err))
362
       else
362
       else
363
         resolve(stat)
363
         resolve(stat)
364
     })
364
     })

+ 8
- 9
index.js View File

17
   RNFetchBlobResponseInfo
17
   RNFetchBlobResponseInfo
18
 } from './types'
18
 } from './types'
19
 import URIUtil from './utils/uri'
19
 import URIUtil from './utils/uri'
20
-import StatefulPromise from './class/StatefulPromise.js'
20
+//import StatefulPromise from './class/StatefulPromise.js'
21
 import fs from './fs'
21
 import fs from './fs'
22
 import getUUID from './utils/uuid'
22
 import getUUID from './utils/uuid'
23
 import base64 from 'base-64'
23
 import base64 from 'base-64'
118
  * @param  {string} method     Should be one of `get`, `post`, `put`
118
  * @param  {string} method     Should be one of `get`, `post`, `put`
119
  * @param  {string} url        A file URI string
119
  * @param  {string} url        A file URI string
120
  * @param  {string} headers    Arguments of file system API
120
  * @param  {string} headers    Arguments of file system API
121
- * @param  {any} body       Data to put or post to file systen.
121
+ * @param  {any}    body       Data to put or post to file systen.
122
  * @return {Promise}
122
  * @return {Promise}
123
  */
123
  */
124
 function fetchFile(options = {}, method, url, headers = {}, body):Promise {
124
 function fetchFile(options = {}, method, url, headers = {}, body):Promise {
520
     }
520
     }
521
     /**
521
     /**
522
      * Start read stream from cached file
522
      * Start read stream from cached file
523
-     * @param  {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
524
-     * @param  {Function} fn On data event handler
523
+     * @param  {String} encoding Encode type, should be one of `base64`, `ascii`, `utf8`.
525
      * @return {void}
524
      * @return {void}
526
      */
525
      */
527
-    this.readStream = (encode: 'base64' | 'utf8' | 'ascii'):RNFetchBlobStream | null => {
526
+    this.readStream = (encoding: 'base64' | 'utf8' | 'ascii'):RNFetchBlobStream | null => {
528
       if(this.type === 'path') {
527
       if(this.type === 'path') {
529
-        return readStream(this.data, encode)
528
+        return readStream(this.data, encoding)
530
       }
529
       }
531
       else {
530
       else {
532
         console.warn('RNFetchblob', 'this response data does not contains any available stream')
531
         console.warn('RNFetchblob', 'this response data does not contains any available stream')
539
      * @param  {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
538
      * @param  {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
540
      * @return {String}
539
      * @return {String}
541
      */
540
      */
542
-    this.readFile = (encode: 'base64' | 'utf8' | 'ascii') => {
541
+    this.readFile = (encoding: 'base64' | 'utf8' | 'ascii') => {
543
       if(this.type === 'path') {
542
       if(this.type === 'path') {
544
-        encode = encode || 'utf8'
545
-        return readFile(this.data, encode)
543
+          encoding = encoding || 'utf8'
544
+        return readFile(this.data, encoding)
546
       }
545
       }
547
       else {
546
       else {
548
         console.warn('RNFetchblob', 'this response does not contains a readable file')
547
         console.warn('RNFetchblob', 'this response does not contains a readable file')

+ 2
- 2
ios.js View File

13
 
13
 
14
 /**
14
 /**
15
  * Open a file using UIDocumentInteractionController
15
  * Open a file using UIDocumentInteractionController
16
- * @param  {string]} path Path of the file to be open.
16
+ * @param  {string} path Path of the file to be open.
17
  * @param  {string} scheme URI scheme that needs to support, optional
17
  * @param  {string} scheme URI scheme that needs to support, optional
18
  * @return {Promise}
18
  * @return {Promise}
19
  */
19
  */
26
 
26
 
27
 /**
27
 /**
28
  * Preview a file using UIDocumentInteractionController
28
  * Preview a file using UIDocumentInteractionController
29
- * @param  {string]} path Path of the file to be open.
29
+ * @param  {string} path Path of the file to be open.
30
  * @param  {string} scheme URI scheme that needs to support, optional
30
  * @param  {string} scheme URI scheme that needs to support, optional
31
  * @return {Promise}
31
  * @return {Promise}
32
  */
32
  */

+ 8
- 8
ios/RNFetchBlob/RNFetchBlob.m View File

194
     if(path) {
194
     if(path) {
195
         resolve(path);
195
         resolve(path);
196
     } else {
196
     } else {
197
-        reject(@"RNFetchBlob file not found", @"could not find path for app group", nil);
197
+        reject(@"RNFetchBlob pathForAppGroup Error", @"could not find path for app group", nil);
198
     }
198
     }
199
 }
199
 }
200
 
200
 
223
     BOOL isDir = nil;
223
     BOOL isDir = nil;
224
     BOOL exist = [fm fileExistsAtPath:path isDirectory:&isDir];
224
     BOOL exist = [fm fileExistsAtPath:path isDirectory:&isDir];
225
     if( exist == NO || isDir == YES) {
225
     if( exist == NO || isDir == YES) {
226
-        callback(@[[NSString stringWithFormat:@"target path `%@` may not exists or it's a folder", path]]);
226
+        callback(@[[NSString stringWithFormat:@"target path `%@` may not exist or it is a folder", path]]);
227
         return;
227
         return;
228
     }
228
     }
229
     NSString * streamId = [fileStream openWithPath:path encode:encoding appendData:append];
229
     NSString * streamId = [fileStream openWithPath:path encode:encoding appendData:append];
326
 
326
 
327
             exist = [fm fileExistsAtPath:path isDirectory:&isDir];
327
             exist = [fm fileExistsAtPath:path isDirectory:&isDir];
328
             if(exist == NO) {
328
             if(exist == NO) {
329
-                callback(@[[NSString stringWithFormat:@"failed to stat path `%@` for it is not exist or it is not exist", path]]);
329
+                callback(@[[NSString stringWithFormat:@"failed to stat path `%@` because it does not exist or it is not a folder", path]]);
330
                 return ;
330
                 return ;
331
             }
331
             }
332
             result = [RNFetchBlobFS stat:path error:&error];
332
             result = [RNFetchBlobFS stat:path error:&error];
362
 
362
 
363
     exist = [fm fileExistsAtPath:path isDirectory:&isDir];
363
     exist = [fm fileExistsAtPath:path isDirectory:&isDir];
364
     if(exist == NO) {
364
     if(exist == NO) {
365
-        callback(@[[NSString stringWithFormat:@"failed to list path `%@` for it is not exist or it is not exist", path]]);
365
+        callback(@[[NSString stringWithFormat:@"failed to lstat path `%@` because it does not exist or it is not a folder", path]]);
366
         return ;
366
         return ;
367
     }
367
     }
368
     NSError * error = nil;
368
     NSError * error = nil;
447
     [RNFetchBlobFS readFile:path encoding:encoding onComplete:^(id content, NSString * err) {
447
     [RNFetchBlobFS readFile:path encoding:encoding onComplete:^(id content, NSString * err) {
448
         if(err != nil)
448
         if(err != nil)
449
         {
449
         {
450
-            reject(@"RNFetchBlob failed to read file", err, nil);
450
+            reject(@"RNFetchBlob readFile Error", err, nil);
451
             return;
451
             return;
452
         }
452
         }
453
         if(encoding == @"ascii")
453
         if(encoding == @"ascii")
529
       });
529
       });
530
         resolve(@[[NSNull null]]);
530
         resolve(@[[NSNull null]]);
531
     } else {
531
     } else {
532
-        reject(@"RNFetchBlob could not open document", @"scheme is not supported", nil);
532
+        reject(@"RNFetchBlob previewDocument Error", @"scheme is not supported", nil);
533
     }
533
     }
534
 }
534
 }
535
 
535
 
549
         });
549
         });
550
         resolve(@[[NSNull null]]);
550
         resolve(@[[NSNull null]]);
551
     } else {
551
     } else {
552
-        reject(@"RNFetchBlob could not open document", @"scheme is not supported", nil);
552
+        reject(@"RNFetchBlob openDocument Error", @"scheme is not supported", nil);
553
     }
553
     }
554
 }
554
 }
555
 
555
 
563
     {
563
     {
564
         resolve(@[[NSNull null]]);
564
         resolve(@[[NSNull null]]);
565
     } else {
565
     } else {
566
-        reject(@"RNFetchBlob could not open document", [error description], nil);
566
+        reject(@"RNFetchBlob excludeFromBackupKey Error", [error description], nil);
567
     }
567
     }
568
 
568
 
569
 }
569
 }

+ 15
- 15
ios/RNFetchBlobFS.m View File

163
             {
163
             {
164
                 if([[NSFileManager defaultManager] fileExistsAtPath:path] == NO)
164
                 if([[NSFileManager defaultManager] fileExistsAtPath:path] == NO)
165
                 {
165
                 {
166
-                    NSString * message = [NSString stringWithFormat:@"File not exists at path %@", path];
166
+                    NSString * message = [NSString stringWithFormat:@"File does not exist at path %@", path];
167
                     NSDictionary * payload = @{ @"event": FS_EVENT_ERROR, @"detail": message };
167
                     NSDictionary * payload = @{ @"event": FS_EVENT_ERROR, @"detail": message };
168
                     [event sendDeviceEventWithName:streamId body:payload];
168
                     [event sendDeviceEventWithName:streamId body:payload];
169
                     free(buffer);
169
                     free(buffer);
254
                     [asciiArray addObject:[NSNumber numberWithChar:bytePtr[i]]];
254
                     [asciiArray addObject:[NSNumber numberWithChar:bytePtr[i]]];
255
                 }
255
                 }
256
             }
256
             }
257
-            
257
+
258
             NSDictionary * payload = @{ @"event": FS_EVENT_DATA,  @"detail" : asciiArray };
258
             NSDictionary * payload = @{ @"event": FS_EVENT_DATA,  @"detail" : asciiArray };
259
             [event sendDeviceEventWithName:streamId body:payload];
259
             [event sendDeviceEventWithName:streamId body:payload];
260
         }
260
         }
261
-        
261
+
262
     }
262
     }
263
     @catch (NSException * ex)
263
     @catch (NSException * ex)
264
     {
264
     {
335
     @try {
335
     @try {
336
         NSFileManager * fm = [NSFileManager defaultManager];
336
         NSFileManager * fm = [NSFileManager defaultManager];
337
         NSError * err = nil;
337
         NSError * err = nil;
338
-        // check if the folder exists, if not exists, create folders recursively
338
+        // check if the folder exists, if it does not exist create folders recursively
339
         // after the folders created, write data into the file
339
         // after the folders created, write data into the file
340
         NSString * folder = [path stringByDeletingLastPathComponent];
340
         NSString * folder = [path stringByDeletingLastPathComponent];
341
         encoding = [encoding lowercaseString];
341
         encoding = [encoding lowercaseString];
452
         else
452
         else
453
         {
453
         {
454
             if(![[NSFileManager defaultManager] fileExistsAtPath:path]) {
454
             if(![[NSFileManager defaultManager] fileExistsAtPath:path]) {
455
-                onComplete(nil, @"file not exists");
455
+                onComplete(nil, @"file does not exist");
456
                 return;
456
                 return;
457
             }
457
             }
458
             fileContent = [NSData dataWithContentsOfFile:path];
458
             fileContent = [NSData dataWithContentsOfFile:path];
459
-            
459
+
460
         }
460
         }
461
-        
461
+
462
         if(encoding != nil)
462
         if(encoding != nil)
463
         {
463
         {
464
             if([[encoding lowercaseString] isEqualToString:@"utf8"])
464
             if([[encoding lowercaseString] isEqualToString:@"utf8"])
485
         {
485
         {
486
             onComplete(fileContent, nil);
486
             onComplete(fileContent, nil);
487
         }
487
         }
488
-        
488
+
489
     }];
489
     }];
490
 }
490
 }
491
 
491
 
495
 + (BOOL) mkdir:(NSString *) path {
495
 + (BOOL) mkdir:(NSString *) path {
496
     BOOL isDir;
496
     BOOL isDir;
497
     NSError * err = nil;
497
     NSError * err = nil;
498
-    // if temp folder not exists, create one
498
+    // if temp folder does not exist create it
499
     if(![[NSFileManager defaultManager] fileExistsAtPath: path isDirectory:&isDir]) {
499
     if(![[NSFileManager defaultManager] fileExistsAtPath: path isDirectory:&isDir]) {
500
         [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&err];
500
         [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&err];
501
     }
501
     }
571
     NSData * decodedData = nil;
571
     NSData * decodedData = nil;
572
     if([[self.encoding lowercaseString] isEqualToString:@"base64"]) {
572
     if([[self.encoding lowercaseString] isEqualToString:@"base64"]) {
573
         decodedData = [[NSData alloc] initWithBase64EncodedString:chunk options: NSDataBase64DecodingIgnoreUnknownCharacters];
573
         decodedData = [[NSData alloc] initWithBase64EncodedString:chunk options: NSDataBase64DecodingIgnoreUnknownCharacters];
574
-    } 
574
+    }
575
     else if([[self.encoding lowercaseString] isEqualToString:@"utf8"]) {
575
     else if([[self.encoding lowercaseString] isEqualToString:@"utf8"]) {
576
         decodedData = [chunk dataUsingEncoding:NSUTF8StringEncoding];
576
         decodedData = [chunk dataUsingEncoding:NSUTF8StringEncoding];
577
     }
577
     }
632
             NSFileManager * fm = [NSFileManager defaultManager];
632
             NSFileManager * fm = [NSFileManager defaultManager];
633
             NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
633
             NSOutputStream * os = [[NSOutputStream alloc] initToFileAtPath:dest append:NO];
634
             [os open];
634
             [os open];
635
-            // abort for the source file not exists
635
+            // abort because the source file does not exist
636
             if([fm fileExistsAtPath:path] == NO)
636
             if([fm fileExistsAtPath:path] == NO)
637
             {
637
             {
638
-                reject(@"RNFetchBlob slice failed : the file does not exists", path, nil);
638
+                reject(@"RNFetchBlob slice Error : the file does not exist", path, nil);
639
                 return;
639
                 return;
640
             }
640
             }
641
             long size = [fm attributesOfItemAtPath:path error:nil].fileSize;
641
             long size = [fm attributesOfItemAtPath:path error:nil].fileSize;
712
         }
712
         }
713
         else
713
         else
714
         {
714
         {
715
-            reject(@"slice error",  [NSString stringWithFormat: @"could not resolve URI %@", path ], nil);
715
+            reject(@"RNFetchBlob slice Error",  [NSString stringWithFormat: @"could not resolve URI %@", path ], nil);
716
         }
716
         }
717
 
717
 
718
     }];
718
     }];
765
     if (dictionary) {
765
     if (dictionary) {
766
         NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
766
         NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
767
         NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
767
         NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
768
-        
768
+
769
         callback(@[[NSNull null], @{
769
         callback(@[[NSNull null], @{
770
                   @"free" : freeFileSystemSizeInBytes,
770
                   @"free" : freeFileSystemSizeInBytes,
771
                   @"total" : fileSystemSizeInBytes,
771
                   @"total" : fileSystemSizeInBytes,
793
     return;
793
     return;
794
 }
794
 }
795
 
795
 
796
-@end
796
+@end

+ 5
- 2
json-stream.js View File

2
 import XMLHttpRequest from './polyfill/XMLHttpRequest'
2
 import XMLHttpRequest from './polyfill/XMLHttpRequest'
3
 import URIUtil from './utils/uri'
3
 import URIUtil from './utils/uri'
4
 
4
 
5
-const OboeExtended = (arg: string | object) => {
5
+const OboeExtended = (arg: string | Object) => {
6
 
6
 
7
 
7
 
8
   window.location = ''
8
   window.location = ''
9
 
9
 
10
   if(!window.XMLHttpRequest.isRNFBPolyfill ) {
10
   if(!window.XMLHttpRequest.isRNFBPolyfill ) {
11
     window.XMLHttpRequest = XMLHttpRequest
11
     window.XMLHttpRequest = XMLHttpRequest
12
-    console.warn('Use JSONStream will automatically replace window.XMLHttpRequest with RNFetchBlob.polyfill.XMLHttpRequest. You are seeing this warning because you did not replace it maually.')
12
+    console.warn(
13
+        'Use JSONStream will automatically replace window.XMLHttpRequest with RNFetchBlob.polyfill.XMLHttpRequest. ' +
14
+        'You are seeing this warning because you did not replace it manually.'
15
+    )
13
   }
16
   }
14
 
17
 
15
   if(typeof arg === 'string') {
18
   if(typeof arg === 'string') {

+ 1
- 1
package.json View File

1
 {
1
 {
2
   "name": "react-native-fetch-blob",
2
   "name": "react-native-fetch-blob",
3
-  "version": "0.10.7",
3
+  "version": "0.10.8",
4
   "description": "A module provides upload, download, and files access API. Supports file stream read/write for process large files.",
4
   "description": "A module provides upload, download, and files access API. Supports file stream read/write for process large files.",
5
   "main": "index.js",
5
   "main": "index.js",
6
   "scripts": {
6
   "scripts": {