MCPcopy Create free account
hub / github.com/BruceDevices/firmware / native_storageWrite

Function native_storageWrite

src/modules/bjs_interpreter/storage_js.cpp:91–149  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

89}
90
91JSValue native_storageWrite(JSContext *ctx, JSValue *this_val, int argc, JSValue *argv) {
92 (void)this_val;
93 // usage: storageWrite(path: string | Path, data: string, mode: "write" | "append", position: number |
94 // string)
95
96 size_t dataSize = 0;
97 const char *dataPtr = NULL;
98 JSCStringBuf sb;
99 if (argc > 0 && JS_IsString(ctx, argv[1])) { dataPtr = JS_ToCStringLen(ctx, &dataSize, argv[1], &sb); }
100
101 FileParamsJS fileParams = js_get_path_from_params(ctx, argv, true);
102 if (!fileParams.path.startsWith("/")) fileParams.path = "/" + fileParams.path;
103
104 const char *mode = FILE_APPEND; // default append
105 if (argc > 2 && JS_IsString(ctx, argv[2])) {
106 JSCStringBuf mb;
107 const char *modeString = JS_ToCString(ctx, argv[2], &mb);
108 if (modeString && modeString[0] == 'w') mode = FILE_WRITE;
109 }
110
111 File file = (fileParams.fs)->open(fileParams.path, mode, true);
112 if (!file) { return JS_NewBool(false); }
113
114 // Check if position is provided
115 if (argc > 3 && JS_IsNumber(ctx, argv[3])) {
116 int64_t pos;
117 int tmp;
118 JS_ToInt32(ctx, &tmp, argv[3]);
119 pos = tmp;
120 if (pos < 0) {
121 file.seek(file.size() + pos, SeekSet);
122 } else {
123 file.seek(pos, SeekSet);
124 }
125 } else if (argc > 3 && JS_IsString(ctx, argv[3])) {
126 size_t tmpSize = 0;
127 char *fileContent = readBigFile(fileParams.fs, fileParams.path, false, &tmpSize);
128 if (fileContent == NULL) {
129 file.close();
130 return JS_ThrowTypeError(
131 ctx, "%s: Could not read file: %s", "storageWrite", fileParams.path.c_str()
132 );
133 }
134 JSCStringBuf sb2;
135 const char *needle = JS_ToCString(ctx, argv[3], &sb2);
136 char *foundPos = strstr(fileContent, needle);
137 if (foundPos) {
138 file.seek(foundPos - fileContent, SeekSet);
139 } else {
140 file.seek(0, SeekEnd);
141 }
142 free(fileContent);
143 }
144
145 if (dataPtr != NULL && dataSize > 0) { file.write((const uint8_t *)dataPtr, dataSize); }
146 file.close();
147
148 return JS_NewBool(true);

Callers 1

native_httpFetchFunction · 0.85

Calls 5

js_get_path_from_paramsFunction · 0.85
readBigFileFunction · 0.85
sizeMethod · 0.80
closeMethod · 0.80
writeMethod · 0.45

Tested by

no test coverage detected