【问题标题】:Node.js Buffer is undefined inside of a ClassNode.js 缓冲区在类中未定义
【发布时间】:2021-11-07 03:40:56
【问题描述】:

我正在用 node.js 编写一个服务器。它在 Buffer 对象中向连接的客户端描述了一个 3D World

这是我的代码。

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;

在另一个文件中,然后我可以

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

但是,当尝试对缓冲区执行任何操作时,我会收到与未定义值相关的错误。

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

我以为我的节点安装坏了,所以我尝试用内容制作一个文件:

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

但这有效:

<Buffer 00 00 00 00 00 00 00 00>

然后我尝试编辑我的代码以在类外初始化Buffer

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

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

这产生了这个结果:

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

谁能解释我做错了什么?这以前有效,所以我唯一能想到的就是将其移动到 Class 以某种方式破坏 Buffers。

【问题讨论】:

    标签: javascript node.js sockets buffer undefined


    【解决方案1】:

    在您的 try/catch 块中,您将 this.data 设置为等于 this.load 的返回值。在 this.load 中你没有返回任何东西,这意味着函数将返回 undefined。你有两种方法可以解决这个问题:

    在 this.load 中,您可以简单地返回值而不是设置 this.data 给它。

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

    或者,更简单,只需删除 this.data = this.load() 并简单地调用 this.load

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

    【讨论】:

    • 非常感谢!当我将它转移到一个班级时,这是一个错误:之前它只是data = zlib.gunzipSync(filesystem.readFileSync( ...
    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2022-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多