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?

2
  • 1. That's not how you add entries to a map a Map - you need to call Map#set to add them and Map#get to retrieve them. What you have right now is just adding random properties to a random object.
    – VLAZ
    Commented Mar 9, 2022 at 7: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 or Convert Map to JSON object in Javascript
    – VLAZ
    Commented Mar 9, 2022 at 7:01

0

Browse other questions tagged or ask your own question.