2

With the regular Object we are able to convert it into JSON string before saving it to the disk but the Map is not an entirely new thing and it cannot always be converted into string (answered here: How do you JSON.stringify an ES6 Map?).

Is it possible to save the Map to the disk as a binary format and read it into a Map later on with Node.js?

Aero Wang
  • 8,382
  • 14
  • 63
  • 99

1 Answers1

1

Is it possible to save the Map to the disk as a binary format and read it into a Map later on with Node.js?

There is no built-in facility for that. A Map is just an association between a set of keys and values. And, if you do

let summaryArray = Array.from(yourMapObject);

summaryArray will be something like this:

[['key1', value1], ['key2', value2]]

Then, assuming your Map object contains things (both keys and values) that can be expressed in JSON (not symbols and not objects with circular references and not custom object types), you can easily save that summaryArray to JSON.

Furthermore, you can regenerate the Map object by reading the JSON from disk, parsing it back into the summaryArray form and passing that to the Map constructor.

let yourMapObject = new Map(summaryArray);

If your Map object does contain things that can't be expressed in JSON, then you will have to invent your own way of storing those things or converting them to/from something that can be expressed in JSON.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • I am aware of `Array.from` method. The reason I asked the question precisely because I do have `Map object does contain things that can't be expressed in JSON` such as: another Map. – Aero Wang Mar 30 '20 at 06:45
  • @AeroWang - Well, an embedded Map can also be converted in the same way. You just have to write the code to traverse it and convert them. There is no automatic binary format for any Javascript objects. If you want to save data in binary format, you have to extract the data yourself, make your own data format, write it out in that format, then write code to do the reverse when reading it and reconstituting the right kinds of objects. – jfriend00 Mar 30 '20 at 06:51
  • I see. `traverse it and convert them` this sounds a bit inconvenient and inefficient... `no automatic binary format for any Javascript objects` that's very unfortunate... – Aero Wang Mar 30 '20 at 07:14
  • @AeroWang - It's just programming work. Unlike some other systems, Javascript does not contain support for automatically serializing objects to a persistent format. JSON was invented to cover a partial subset. Anything beyond that needs more code to convert things appropriately. There are LOTS of serialization libraries already written for this type of thing. I'm not familiar with any of them, but see lots of choices in a Google search. – jfriend00 Mar 30 '20 at 07:19