Problem with saving the file with modified data
How can save nbt file?
The file is "level.dat" from Minecraft world, it should be compressed in gzip.
I’ve tried nbt-js with zlib:
var fs = require('fs');
var zlib = require('zlib');
var nbt = require('nbt-js');
var file = fs.readFileSync('level.dat');
var level = zlib.gunzipSync(file);
var tag = nbt.read(level);
console.log(JSON.stringify(tag.payload[''].Data.Time, null, 4));
And I can see and modify the data, but how can I compress it again and save it as "level.dat"?
2
Answers
I’ve been working on a library to do this same task with my own NBT files too. Here’s a demo I made that accomplishes what your question is about.
My NBT library handles the compression part for you, so there’s no need to decompress the file manually before opening it. It will also compress it back to the same format it was already in, when writing back to the file system.
The package can be installed from npm as
nbtify
. It’s built using the ES Module syntax, so the only hang up is that it has to be imported using theimport()
function syntax when importing it into a CommonJS module. That’s why I wrapped the script in an async IIFE.The NBT
LongTag
type, which is the type of value forlevelDat.Data.Time
, is represented by the BigInt number primitive when usingnbtify
.To change the value of
levelDat.Data.Time
, you can declare your new value on the NBT object using dot notation, as seen below. Declaring a number using the BigInt primitive can be done by addingn
to the end of a number literal.