N
N
Night_Harpy2021-01-16 13:26:43
Node.js
Night_Harpy, 2021-01-16 13:26:43

How to make the file replenished and not overwritten?

I want the file to be constantly updated by new users, but in fact, it is overwritten every time by a new user, how can I solve the problem?

addUser = (user) => {
        const addUsers = {
            table:[]
        };        
        addUsers.table.push(user);      
        const users = fs.writeFile('name.json', JSON.stringify(addUsers, null, 3), (err) => {
            if(err) throw err;
        });        
        return users        
    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Yarkov, 2021-01-16
@Night_Harpy

So you add one user to the empty array each time and write to the file. It is necessary to read from a file into an array, and then add a user and save to a file.

L
Lynn "Coffee Man", 2021-01-16
@Lynn

1. Read and parse the file
2. Add the user to the object obtained in step 1
3. Save the object to a file. (and pray that at that moment another request did not overwrite the file)
Or throw out this nonsense and take the database (yes, at least the same sqlite)

A
Alexey, 2021-01-16
@Azperin

https://nodejs.org/api/fs.html#fs_fs_appendfile_pa...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question