Use the fs/promises node API to Serialize a Map to the Filesystem

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

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.

In future lessons we'll use this class to persist our in-memory notes.

View the source for MapStore.js on the projects github repo.

Jamund Ferguson: [0:00] 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.

[0:19] 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.

[0:37] 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.

[0:47] 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.

[1:04] 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.

[1:26] 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.