skip to Main Content

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


  1. Chosen as BEST ANSWER
    fs.writeFileSync('level1.dat', zlib.gzipSync(nbt.write(tag.payload, tag.schema)));
    

  2. 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 the import() 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 for levelDat.Data.Time, is represented by the BigInt number primitive when using nbtify.

    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 adding n to the end of a number literal.

    (async function(){
    
    var fs    = require('fs');
    var NBT   = await import('nbtify');
    var file  = fs.readFileSync('level.dat');
    var tag   = await NBT.read(file);
    console.log('Time (Original) =>', tag.data.Data.Time);
    
    // BigInt number type
    tag.data.Data.Time = 12345n;
    console.log('Time (Edited) =>', tag.data.Data.Time);
    
    var editedFile = await NBT.write(tag);
    fs.writeFileSync('level-edited.dat',editedFile);
    
    })();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search