Storing data in a TypeBuffer and then retrieving it from a file can lead to surprising outcomes

Upon executing the following code:

var list = new Uint32Array(16);
for (var i=0; i<16; ++i) list[i] = i;
fs.writeFileSync("list", new Uint8Array(list).buffer);
console.log([].slice.call(new Uint32Array(fs.readFileSync("list"))));

We anticipate the output to be:

[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]

However, what is actually generated is:

[ 91, 111, 98, 106, 101, 99, 116, 32, 65, 114, 114, 97, 121, 66, 117, 102, 102, 101, 114, 93 ]

A detailed view of the list file exhibits this:

0000000 5b 6f 62 6a 65 63 74 20 41 72 72 61 79 42 75 66
0000010 66 65 72 5d                                    

What could be causing the disparity between the expected and actual results?

Answer №1

The property known as buffer within a TypedArray (specifically Uint8Array) refers to an ArrayBuffer, which differs from the node.js Buffer. If attempting to manipulate data between an ArrayBuffer and a file using the fs module that expects a node.js Buffer, it will not function properly.

To address this issue, various methods are available for converting between the two types. The most straightforward solution to ensure the expected functionality is to create a new Buffer object using the original arr array instead of relying on the .buffer property:

var arr = new Uint32Array(16);
for (var i=0; i<16; ++i) arr[i] = i;
fs.writeFileSync("arr", new Buffer(arr)); // <-- HERE
console.log([].slice.call(new Uint32Array(fs.readFileSync("arr"))));

Output:

[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]

Additionally, a hexadecimal representation of the contents in the resulting file named arr appears as follows:

0000000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Svelte to effectively connect to a specified object within an array

Check out this code snippet: <script> let data = [ {id: 1, first: "x"}, {id: 2, second: "y"} ]; </script> <input type="text" bind:value={data.first}/> If you modify the value in the input field and ...

Utilize a Vue.js filter on the v-model within an input element

Seeking assistance! I successfully created a directive that wraps the Jasny Bootstrap Plugin, specifically focusing on the input mask feature! Additionally, I have developed a custom filter using moment to format date fields! The date format received fro ...

Integrate, Delay, Experimentalize, and Attach components

This inquiry might lean more towards a general browser/javascript discussion rather than a focused prototype question, but I believe this community possesses a deep understanding of javascript and browsers. With that said, here is my query: If the followi ...

Modify the onerror function of the image tag within the onerror function

Here is a way to display images using the img tag: If 1.jpg exists, show 1.jpg. If not, check for 2.jpg and display it if it exists. If neither 1.jpg nor 2.jpg exist, display 3.jpg. <img src="1.jpg" onerror="this.src='2.jpg'; this.oner ...

What is the best way to transform a string representation of data into an array and then showcase it in

After importing CSV data and converting it into the variable stringData, I am facing an issue when trying to display this data in a React table. Although I have attempted to use the map function to separate the headers and map to <th>, displaying t ...

Jenkins Node Version Switch: No executables were located in the directory "/usr/local/n/versions/node/11.15.0/bin"

Every time I run my Jenkins pipeline, I keep encountering the following error: Couldn’t find any executable in "/usr/local/n/versions/node/11.15.0/bin" The Jenkins Slave is set up on an AWS Linux machine with both node 16.x and node 11.15.0 in ...

Browserify pulls in entire module even if only specific parts are utilized, such as react-addons

I am currently using Browserify to bundle my server-side react.js code for the client. There is a concern that utilizing a module from an npm package may result in the entire package being bundled by Browserify. Question: Will require('react-addons& ...

Accessing the various types within a monorepo from a sibling directory located below the root folder

Seeking assistance in resolving a referencing types issue within a TypeScript monorepo project. Unsure if it is feasible given the current setup. The project structure is as follows: . ├── tsconfig.json ├── lib/ │ └── workers/ │ ...

Obtaining a cookie in Vue.js independently: a step-by-step guide

After setting a cookie using laravel, I'm looking to retrieve it in vue.js without relying on or installing any external dependencies. Can anyone please suggest a way to achieve this without extra tools? Your guidance would be greatly appreciated! ...

Get the latest html content and save it as a .html file using javascript or jQuery

Looking for a way to save an HTML page as a .html file? Having some trouble with jQuery modifications not being included in the exported file? Check out the code snippet below and let me know if you can spot what's going wrong! I'm still getting ...

Error in NodeJs: ReferenceError - the variable I created is not defined

Encountering an issue while attempting to use a module in my router file. I have successfully required it, but now I am seeing the following error message: ReferenceError: USERS is not defined at c:\work\nodejs\router\main.js:32 ...

Guide to referencing the same schema as a type in Mongoose

I have created a list of objects called Comments Objects in which comments are stored, and whenever someone replies to a comment, it gets stored in the children section. { "_id": "5dbc479babc1c22683b73cf3", "comment": "wow .. this is awesome", ...

Avoid unnecessary re-renders in ReactJS Material UI tabs when pressing the "Enter

I've created a user interface with tabs using material-ui in reactJS. The issue I'm facing is that every time a tab is selected, the content under that tab reloads, causing performance problems because there's an iFrame displayed in one of t ...

What is the best way to obtain the attribute value when a user clicks on a child element?

Is there a way to retrieve the value of the data-custom attribute when the red square is clicked without having to add the same attribute to nested elements? This can become cumbersome if there are multiple levels of nesting. class Example extends React ...

Enigmatic void appears above row upon removal of content from a single item

When I click on an item in my grid, the content of that item is moved to a modal. The modal functions properly, but I noticed that when the content is removed from the item, a space appears above it. I have found that using flexbox could solve this issue, ...

Generating dynamic dropdown menus using data from a database with the help of PHP and Ajax technologies

I'm currently working on creating a dynamic dropdown menu that will be populated with data retrieved from a database. I've hit a roadblock in parsing the data from a multidimensional array sent by a PHP file. Here's a snippet of my code: Se ...

PHP Bootstrap Confirmation Dialog Tutorial

Is there a way to implement a delete confirmation dialog? When 'yes' is clicked, the message should be deleted, and when 'no' is clicked, the delete operation should be canceled. At present, this is how it looks in my view: <a href ...

Eliminable Chips feature in the Material UI Multiple Select component

The Material UI documentation showcases a multiple select example where the selected options are displayed using the Chip component and the renderValue prop on the Select. By default, clicking on the current value opens the list of available options. I am ...

Vue.js Interval Functionality Malfunctioning

I'm brand new to Vuejs and I'm attempting to set an interval for a function, but unfortunately it's not working as expected. Instead, I am encountering the following error: Uncaught TypeError: Cannot read property 'unshift' of u ...

What are some ways to create a versatile wrapper?

I'm currently grappling with an issue involving my Formik fields. I need to utilize FastFields in certain scenarios and Fields in others within my FormikControl, a class designed for constructing formik inputs. The challenge lies in being able to swit ...