MCPcopy Create free account
hub / github.com/buke/quickjs-go / js_std_writeFile

Function js_std_writeFile

deps/quickjs/quickjs-libc.c:570–629  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

568}
569
570static JSValue js_std_writeFile(JSContext *ctx, JSValueConst this_val,
571 int argc, JSValueConst *argv)
572{
573 const char *filename;
574 const char *mode;
575 const void *buf;
576 size_t len, n;
577 JSValueConst data;
578 JSValue val, ret, unref;
579 bool release;
580 FILE *fp;
581
582 ret = JS_EXCEPTION;
583 len = 0;
584 buf = "";
585 mode = "w";
586 data = argv[1];
587 unref = JS_UNDEFINED;
588 release = false;
589 filename = JS_ToCString(ctx, argv[0]);
590 if (!filename)
591 return JS_EXCEPTION;
592 if (JS_IsObject(data)) {
593 val = JS_GetPropertyStr(ctx, data, "buffer");
594 if (JS_IsException(val))
595 goto exception;
596 if (JS_IsArrayBuffer(val)) {
597 data = unref = val;
598 } else {
599 JS_FreeValue(ctx, val);
600 }
601 }
602 if (JS_IsArrayBuffer(data)) {
603 buf = JS_GetArrayBuffer(ctx, &len, data);
604 mode = "wb";
605 } else if (!JS_IsUndefined(data)) {
606 buf = JS_ToCStringLen(ctx, &len, data);
607 release = true;
608 }
609 if (!buf)
610 goto exception;
611 fp = fopen(filename, mode);
612 if (!fp) {
613 JS_ThrowPlainError(ctx, "error opening %s for writing", filename);
614 goto exception;
615 }
616 n = fwrite(buf, len, 1, fp);
617 fclose(fp);
618 if (n != 1) {
619 JS_ThrowPlainError(ctx, "error writing to %s", filename);
620 goto exception;
621 }
622 ret = JS_UNDEFINED;
623exception:
624 JS_FreeCString(ctx, filename);
625 if (release)
626 JS_FreeCString(ctx, buf);
627 JS_FreeValue(ctx, unref);

Callers

nothing calls this directly

Calls 5

JS_ToCStringFunction · 0.85
JS_IsObjectFunction · 0.85
JS_IsExceptionFunction · 0.85
JS_IsUndefinedFunction · 0.85
JS_ToCStringLenFunction · 0.85

Tested by

no test coverage detected