Is there a way to read & write a 2d array to a .db or .txt file in node.js

Viewed 201

I am really new to this field just started my first project and instead of using complex data base's I just want to store a simple 2d array (table) to file so that I can retrieve it later, I did look at fs.writeFile but it doesn't seem to accept arrays in this format...

I am really new to this field so if there are any other ways of storing data or if this is a really bad way to store data then please suggest me what to do

var myArray = [
["bob","john","jack"],
[62,31,11],
["employed","unemployed","uneligible"],
["engineer","doctor","student"],
["21/09/2021","28/11/2021","16/12/2021"]]

how can I save this as it is to a file (any file) for later use

// something like this 

writeToFile( "./info.db" , myArray )

// inside the file info.db
[["bob","john","jack"],[62,31,11],["employed","unemployed","uneligible"],["engineer","doctor","student"],["21/09/2021","28/11/2021","16/12/2021"]]

and also to get this array back as an array , i did try using readFileSync with utf8 encoding but i got the data back as a buffer as such when i try to read the data[0] i get this the first character of the string " [ "

1 Answers

This is because fs.writeFile accepts a string as the second argument. So we can instead JSON.stringify the data instead of writing the raw JS object.

const { writeFileSync } = require('fs');

var myArray = [
    ["bob","john","jack"],
    [62,31,11],
    ["employed","unemployed","uneligible"],
    ["engineer","doctor","student"],
    ["21/09/2021","28/11/2021","16/12/2021"]
];

writeFileSync('./info.db', JSON.stringify(myArray));

Just in general, using JSON as a big database isn't a good practice because

  • First of all, it is not relational
  • It is not a DBMS, it is a data format.
Related