我正在用 node.js 撰寫一個服務器。它World在Buffer物件中向連接的客戶端描述 3D 。
這是我的代碼。
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
有人可以解釋我做錯了什么嗎?這以前有用過,所以我唯一能想到的就是以某種方式將它移動到一個Classbroken Buffers。
uj5u.com熱心網友回復:
在您的 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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/350997.html
標籤:javascript 节点.js 插座 缓冲 不明确的
