0

Title says all, i'm trying to put objects into files based on their dates. For exmaple, I have files named "May 23","May 24","May 25" ect ect. My objects (in simplest terms) looks like this:

{id: 1, mintDate: May 23},{id: 1, mintDate: May 24},{id: 1, mintDate: May 25}

Now I want to put each object, into its respective file. for example, the {id: 1, date: May 23} object should go into the "May 23" file.

What my current code does, is for each file, it puts ALL three objects into each file. In my code, i'm not sure where i need to put the conditional to check if the date of the project is ALSO the date of the file. This is what i have currently, this all works fine without error.

        for(o in collections){
            const collection = collections[o]

            fs.readFile(__dirname + "/HowIsCollections/"+collection.mintDate,'utf8',function(err,data){
                const dat = JSON.parse(data)
                const existedData = []

                for(i in dat){
                    existedData.push(JSON.stringify(dat[i]))
                }


                const project = JSON.stringify(collections)
                if(!existedData.includes(project)){ 
                    console.log("?")
                    dat.push(project)
                }
                fs.writeFileSync(__dirname + "/HowIsCollections/"+collection.mintDate,JSON.stringify(dat)) 

            }) 
        }

I tried looking at these two threads but they didnt seem to be much help. Sort array of objects by string property value and How to sort an object array by date property?

netsocket
  • 117
  • 1
  • 10

1 Answers1

0

Here you go :)

const fs = require("fs")
const path = require("path")

async function main() {
    const input = [
        { id: 1, mintDate: "May 23" },
        { id: 2, mintDate: "May 24" },
        { id: 3, mintDate: "May 25" }
    ]

    for (const part of input) {
        try {
            const previousRawData = await readFileByDate({ date: part.mintDate })
            const currentData = previousRawData.length > 0 ? [...JSON.parse(previousRawData), part] : [part]

            await writeFileByDate({ date: part.mintDate, data: JSON.stringify(currentData) })
        } catch (error) {
            console.log(error)
        }
    }
}

async function readFileByDate({ date, basePath = "." }) {
    const pathOfFile = path.join(__dirname, `${basePath}/${date}.json`)
    return new Promise((resolve, reject) => {
        fs.readFile(pathOfFile, { encoding: 'utf-8' }, (err, data) => {
            if (err)
                return reject(err)
            resolve(data)
        })
    })
}

async function writeFileByDate({ date, data, basePath = "." }) {
    const pathOfFile = path.join(__dirname, `${basePath}/${date}.json`)
    return new Promise((resolve, reject) => {
        fs.writeFile(pathOfFile, data, { encoding: 'utf-8' }, err => {
            if (err)
                return reject(err)
            resolve(true)
        })
    })
}

main()