| 568 | } |
| 569 | |
| 570 | static 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; |
| 623 | exception: |
| 624 | JS_FreeCString(ctx, filename); |
| 625 | if (release) |
| 626 | JS_FreeCString(ctx, buf); |
| 627 | JS_FreeValue(ctx, unref); |
nothing calls this directly
no test coverage detected