1

After running this code:

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

The expected output is:

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

But, instead, it produces this output:

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

A hexdump of the arr file shows this:

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

Why does the produced output not match the expected output?

Mike S
  • 39,439
  • 11
  • 85
  • 82
MaiaVictor
  • 45,122
  • 42
  • 127
  • 254
  • 2
    What have you done to troubleshoot this issue? Did you observe the content of the new `"arr"` file? That should give you a big clue. – cookie monster Sep 20 '14 at 03:27
  • 2
    This problem is incompletely specified. What is the "something else" you are observing? Don't expect people to have to run your code to answer your question. Some people do but realize that a lot of experienced posters on this site answer simply by reading the question (note that a lot of high rep users answer with "this code is not tested" desclaimers) – slebetman Sep 20 '14 at 03:47
  • @Mike that was a very good edit, thanks. – MaiaVictor Sep 20 '14 at 18:20

1 Answers1

2

The buffer property of a TypedArray (Uint8Array in this case) is an ArrayBuffer, which is not the same as a node.js Buffer. If you try to read/write an ArrayBuffer to a file when the fs module is expecting a node.js Buffer, it's not going to work.

However, you can convert between the two any number of ways. The simplest change to your code to make it work as expected would be to simply initialize a Buffer from arr instead of trying to use 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"))));

Outputs:

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

And, for completeness, a hex dump of the arr file looks like:

0000000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
Community
  • 1
  • 1
Mike S
  • 39,439
  • 11
  • 85
  • 82
  • I'd never have guessed that. I always assumed `node.js` Buffers and ArrayBuffers were the same. Thank you very much. – MaiaVictor Sep 20 '14 at 18:21