Home > Software design >  Node.js Buffer is undefined inside of a Class
Node.js Buffer is undefined inside of a Class

Time:11-07

I'm writing a server in node.js. It describes a 3D World to clients who connect, in a Buffer object.

Here is my code.

var zlib = require("zlib");
var filesystem = require("fs");
var path = require("path");

class World {
  constructor(name, x, y, z) {
    this.data = Buffer.alloc(x * y * z);
    this.name = name;
    this.x = x;
    this.y = y;
    this.z = z;
    try {
      this.data = this.load();
    } catch (er) {
      console.warn("Couldn't load world from file, creating new one");
      this.data.fill(0);
    }
  }

  setNode(id, x, y, z) {
    this.data.writeUInt8(id, 4   x   this.z * (z   this.x * y));
  }

  getNode(block, x, y, z) {
    return this.data.readUInt8(4   x   this.z * (z   this.x * y));
  }

  dump() {
    return this.data;
  }

  load() {
    this.data = zlib.gunzipSync(filesystem.readFileSync(path.join(__dirname, `/worlds/${this.name}/world.buf`)));
  }

  save() {
    filesystem.writeFileSync(path.join(__dirname, `/worlds/${this.name}/world.buf`), zlib.gzipSync(this.data));
  }
}

module.exports = World;

in another file, I can then

var World = require("./lib/world.js");
var world = new World('example', 256, 64, 256);

But, when trying to do anything with the buffer, I get errors relating to the value being undefined.

console.log(world.dump());
undefined

I thought my installation of node broke, so I tried making a file with the content:

var test = Buffer.alloc(8);
console.log(test);

but this worked:

<Buffer 00 00 00 00 00 00 00 00>

I then tried editing my code to initialise the Buffer outside of the class:

...
var test = Buffer.alloc(4194304);
console.log(test)

class World {
  constructor(name, x, y, z) {
    this.data = test;
    console.log(this.data);
...

this yielded this result:

Buffer <00 00 00 00 00 00 00 00 [etc]>
undefined

can someone explain what I'm doing wrong? this has worked before so the only thing I can think of is moving it into a Class broke Buffers somehow.

CodePudding user response:

In your try/catch block you are setting this.data equal to the return of this.load. Inside of this.load you are not returning anything, which means the function will return undefined. You have two ways you can fix this:

Inside of this.load you can simply return the value instead of setting this.data to it.

  load() {
    return zlib.gunzipSync(filesystem.readFileSync(path.join(__dirname, `/worlds/${this.name}/world.buf`)));
  }

Or, the easier, just remove the this.data = this.load() and simply call this.load

try {
  this.load();
} catch (er) {
  console.warn("Couldn't load world from file, creating new one");
  this.data.fill(0);
}
  • Related