0

I am facing issue in getting data from a file as a buffer and then converting it into a long sample code is

var fs = require('fs');

fs.open('24.mkt', 'r', function(status, fd) {
  if (status) {
    console.log(status.message);
    return;
  }
  var buffer = new Buffer(4);
  fs.read(fd, buffer, 0, 4, 0, function(err, num) {
    console.log(buffer.values());
  });
});

file link - > https://archive.org/download/kamo_24/24.mkt

first 4 bytes contains Timestamp in Long in 4 Bytes

Rahul Kamboj
  • 449
  • 3
  • 14
  • Possible duplicate of [JavaScript: reading 3 bytes Buffer as an integer](http://stackoverflow.com/questions/30911185/javascript-reading-3-bytes-buffer-as-an-integer) – Juicy Scripter Apr 13 '17 at 10:37

2 Answers2

1

You can use node.js's Buffer.readInt32BE function. It reads 4 bytes in the given order (Big, or Little endian) to a variable, starting at the offset parameter:

// Unix timestamp now: 1492079016
var buffer = Buffer.from([0x58, 0xEF, 0x51, 0xA8]);
var timestamp = buffer.readInt32BE(0);

process.stdout.write(timestamp.toString());
Laposhasú Acsa
  • 1,550
  • 17
  • 18
0

You probably want to use readUInt32BE and/or readUInt32LE (of buffer) to convert buffer values to number.

You may also try to converting a values in a buffer to numeric value using node-bigint or node-bignum (it's probably overkill for a 4 bytes case but if you need to deal with a bigger numbers it may suit the need), both allow creation from buffer in a similar form (just be aware of options differences):

bignum.fromBuffer(buf, opts)
// or
bigint.fromBuffer(buf, opts)
Juicy Scripter
  • 25,778
  • 6
  • 72
  • 93