@@ -7,9 +7,11 @@ import { buffer } from '@kit.ArkTS';
7
7
8
8
export type BlobUtilViewDescriptor = Descriptor < "RNCBlobUtil" >
9
9
export const FAST_BLOB_UTIL = "BlobUtil"
10
+ const FILE_OR_DIR_NOT_EXIST : number = 13900002 ;
10
11
11
12
export type Encoding = "utf8" | "ascii" | "base64" ;
12
13
export type Stream = { encoding :string , stream :fs . Stream | undefined }
14
+
13
15
export interface ReactNativeBlobUtilReadStream {
14
16
path : string ;
15
17
encoding : Encoding ;
@@ -38,25 +40,35 @@ export default class ReactNativeBlobUtilStream {
38
40
}
39
41
40
42
41
- async writeStream ( filePath : string , encoding : string , append : boolean , callback : ( errCode , errMsg , streamId ?: string ) => void ) {
42
- if ( ! fs . accessSync ( filePath ) ) {
43
- callback ( "ENOENT" , "File '" + filePath + "' does not exist and could not be created" ) ;
44
- return
43
+ async writeStream ( filePath : string , encoding : string , append : boolean ,
44
+ callback : ( errCode , errMsg , streamId ?: string ) => void ) {
45
+ let accessRes = fs . accessSync ( filePath ) ;
46
+ let file = fs . openSync ( filePath , fs . OpenMode . READ_WRITE | fs . OpenMode . CREATE ) ;
47
+ if ( append && accessRes ) {
48
+ file = fs . openSync ( filePath , fs . OpenMode . READ_WRITE | fs . OpenMode . APPEND ) ;
45
49
}
46
- let file = fs . openSync ( filePath ) ;
47
50
this . encoding = encoding ;
48
51
try {
49
- let stream = await fs . createStreamSync ( filePath , "a+" )
52
+ let stream = await fs . createStreamSync ( filePath , "a+" ) ;
50
53
let uuid = util . generateRandomUUID ( true ) ;
51
54
ReactNativeBlobUtilStream . fileStreams . set ( uuid , {
52
55
stream : stream ,
53
56
encoding : encoding
54
- } )
55
- this . stream = stream
57
+ } ) ;
58
+ this . stream = stream ;
56
59
fs . closeSync ( file ) ;
57
- callback ( null , null , uuid )
60
+ callback ( null , null , uuid ) ;
58
61
} catch ( err ) {
59
- callback ( "EUNSPECIFIED" , "Failed to create write stream at path `" + filePath + "`; " + err . message ) ;
62
+ if ( err . code === FILE_OR_DIR_NOT_EXIST ) {
63
+ try {
64
+ fs . mkdirSync ( filePath . substring ( 0 , filePath . lastIndexOf ( '/' ) ) , true ) ;
65
+ await this . writeStream ( filePath , encoding , append , callback ) ;
66
+ } catch ( e ) {
67
+ callback ( "EUNSPECIFIED" , "Failed to create write stream at path `" + filePath + "`; " + err . code ) ;
68
+ }
69
+ } else {
70
+ callback ( "EUNSPECIFIED" , "Failed to create write stream at path `" + filePath + "`; " + err . code ) ;
71
+ }
60
72
}
61
73
}
62
74
0 commit comments