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 4 years ago
Updated 3 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.

egghead
egghead
~ 6 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today