【发布时间】: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