Search code examples
node.jsreadfile

What is difference between get data from file and after parse data in byte?


I have some problems with the length in a byte of data get from a file. In my case, I use the readFileSync method to get data from a text file. But when I do something like the below code. It gives me 2 difference results.

let data = fs.readFileSync('size.txt');
console.log(data.length);
console.log(JSON.stringify(JSON.parse(data)).length);

Result in: 579859 (console log 1) and 409065 (console log 2)

So, I don't understand why the size is decreased after I parsed it to JSON and then I use the stringify method.

Thank you for any helping!


Solution

  • JSON.stringify will not restore the spaces like in the below example :

    const obj = `{
      "keyA": "obiwan kenobi",
      "testB": "foo"
    }`;
    
    console.log(obj);
    
    const obj2 = JSON.stringify(JSON.parse(obj));
    
    console.log(obj.length, obj2.length);
    
    console.log(obj2);