Warlockk
Warlockkā€¢2mo ago

I can't write Uint32Array on a file.

I want to write an Uint32Array type to a file, but i always have the following error:
error: Uncaught (in promise) TypeError: expected typed ArrayBufferView
error: Uncaught (in promise) TypeError: expected typed ArrayBufferView
I tried using Deno.writeFileSync and writeFileSync from node:fs, but no one worked. What can I do? It seems like Deno is limiting us to write only the Uint8Array type.
2 Replies
Warlockk
Warlockkā€¢2mo ago
Sorry, here is a minimal example:
import { writeFileSync } from "node:fs";

writeFileSync('.data.bin', Uint32Array.from([1, 2, 3]));
import { writeFileSync } from "node:fs";

writeFileSync('.data.bin', Uint32Array.from([1, 2, 3]));
command:
deno run --allow-all main.ts
deno run --allow-all main.ts
Deno AI Helper
Deno AI Helperā€¢2mo ago
The error you're encountering suggests that the API you're using expects a typed array that is a view on an ArrayBuffer, such as Uint8Array. According to the documentation, Deno's writeFile and writeFileSync functions indeed work with Uint8Array. If you want to write a Uint32Array to a file, you will need to convert it to a Uint8Array first. Here's how you can convert a Uint32Array to a Uint8Array and then write it to a file in Deno:
const uint32Array = new Uint32Array([72, 101, 108, 108, 111]); // Your Uint32Array
const buffer = new Uint8Array(uint32Array.buffer);

// Now you can write the buffer to a file
await Deno.writeFile("hello.txt", buffer);
// Or synchronously
Deno.writeFileSync("hello.txt", buffer);
const uint32Array = new Uint32Array([72, 101, 108, 108, 111]); // Your Uint32Array
const buffer = new Uint8Array(uint32Array.buffer);

// Now you can write the buffer to a file
await Deno.writeFile("hello.txt", buffer);
// Or synchronously
Deno.writeFileSync("hello.txt", buffer);
The uint32Array.buffer is an ArrayBuffer that is the underlying buffer of the Uint32Array. By passing it to the Uint8Array constructor, you create a Uint8Array view on the same buffer, which can then be written to a file using Deno's file writing APIs. Remember to ensure that you have the necessary permissions to write to the file system when running your Deno script. You can do this by including the --allow-write flag when invoking your script:
deno run --allow-write your_script.ts
deno run --allow-write your_script.ts
šŸ¦• If you have any more questions or need further assistance, feel free to ask!