0

I am trying to write the contents of a Map to a text file, but am getting an error. Here is my code:

const dictionary = new Map()
dictionary['foo'] = 10
dictionary['test'] = 5
dictionary['sample'] = 7
require('fs').writeFile('textFile.txt', dictionary, (error) => {
    if(error) throw err
})

The error I get says that I cannot write a Map as the 'data' argument must be of type string or an instance of Buffer, TypedArray, or DataView. Is there a way that I can write the contents of my Map to the 'textFile.txt' file?

  • 1. That's not how you add entries to a map a Map - you need to call [`Map#set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set) to add them and [`Map#get`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get) to retrieve them. What you have right now is just adding random properties to a random object. – VLAZ Mar 09 '22 at 07:01
  • 2. Since `writeFile` wants a string, you can convert the map to a string. And since we don't really know how you want that map represented, we can't tell you exactly what you want to do. But you can start with something like [Create json string from js Map and String](https://stackoverflow.com/q/44740423) or [Convert Map to JSON object in Javascript](https://stackoverflow.com/q/37437805) – VLAZ Mar 09 '22 at 07:01

0 Answers0