Jamund Ferguson: Create a file called MapStore.js. Inside that, we're going to first import { readfile, writefile } from "fs/promises". Also import path from "path". Now type const dataDir = "data". This is where we're going to store our data.
Let's create a MapStore class and create a constructor, which takes in a filename. We're going to save a variable called this.filepath = path.resolve(dataDir, filename). Basically, it gives us the full path to the file that we're going to be writing.
This MapStore class is going to have two methods. It's going to have save, which is going to take some data in the form of a map, and it's going to have a read method as well.
Let's go ahead and fill in save by first logging out what we're saving. Then const serializedData = JSON.stringify(Array.from(data.entries())). That's how we serialize our map.
Then we can say await writeFile(this.filepath, serializedData). Now let's fill in read. We'll console.log('reading' from ${this.filepath}'). We'll type const data = await readFile(this.filepath). For the second argument, we'll type utf-8, which is the encoding type.
Then parse the JSON. Type const parsed = JSON.parse(data). Then we'll pass that parsed data into a new Map. With that, we should enough to both save a map to a file and read that file again.
Duration
2 min
Access
Free
Transcript
Available
Course lesson
Use the fs/promises node API to Serialize a Map to the Filesystem
We create a class called MapStore that serializes the JavaScript Map object to JSON and stores that on the filesystem using node 14's fs/promises API.